在 PHP/HTML 中交替行颜色的最简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/399137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:36:58  来源:igfitidea点击:

Easiest way to alternate row colors in PHP/HTML?

phphtmlcsscolors

提问by thrashr888

Here's a PHP example of mine. Can anyone find a shorter/easier way to do this?

这是我的一个 PHP 示例。谁能找到更短/更简单的方法来做到这一点?

<? foreach($posts as $post){?>
    <div class="<?=($c++%2==1)?‘odd':NULL?>">
        <?=$post?>
    </div>
<? }?>

<style>
    .odd{background-color:red;}
</style>

Examples in other languages would be fun to see as well.

其他语言的例子也会很有趣。

回答by Vilx-

Fundamentally - no. That's about as easy as it gets. You might rewrite it a bit shorter/cleaner, but the idea will be the same. This is how I would write it:

从根本上说 - 没有。这很容易。你可能会改写得更短/更简洁,但想法是一样的。我会这样写:

$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
    echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";

回答by Max

If you'd like to have less in-line PHP, a great way of doing it is via JavaScript.

如果您希望减少内联 PHP,一个很好的方法是通过 JavaScript。

Using jQuery, it's simply:

使用jQuery,它很简单:

<script type="text/javascript">
$('div:odd').css('background-color', 'red');
</script>

回答by Ole Helgesen

Using CSS3 you can do something like this:

使用 CSS3,您可以执行以下操作:

div:nth-child(odd)
{
  background-color: red
}

But better not use that for a few years if you actually want your users to see the color...

但如果你真的想让你的用户看到颜色,最好不要使用它几年......

回答by gak

Smarty has it inbuilt:

Smarty 内置了它:

{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
   <td>{$data[rows]}</td>
</tr>
{/section}

So does Django:

Django 也是如此:

{% for o in some_list %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% endfor %}

回答by nickf

i always name my zebra rows "row0" and "row1" - this makes the code a bit simpler.

我总是将我的斑马行命名为“row0”和“row1”——这使得代码更简单一些。

<?php  // you should always use the full opening tag for compatibility
$i = 0;
foreach ($rows as $row) {
    echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
} 
?>

回答by Jeremy Ruten

Maybe a function with a static variable?

也许是一个带有静态变量的函数?

<?php

function alternate_row_color($css_class) {
    static $show = true;

    $show = !$show;

    if ($show) {
        return $css_class;
    } else {
        return NULL;
    }
}

?>

Then to use it (using your example):

然后使用它(使用您的示例):

<?php foreach($posts as $post) { ?>
    <div class="<?=alternate_row_color('odd')?>">
        <?=$post?>
    </div>
<?php } ?>

回答by navitronic

<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
    <!-- Content --> 
</div>  
<?php endforeach ?>

Would be the simplest and clearest way to do it.

将是最简单和最清晰的方法。

回答by Eineki

Just for fun

只是为了好玩

Assuming you can use CSS3 selectors you can do something like

假设您可以使用 CSS3 选择器,您可以执行以下操作

<div class="posts">
<? foreach($posts as $post){?>
    <div>
        <?=$post?>
    </div>
<? }?>
</div>

<style>
    div.posts div:odd{background-color:red;}
</style>

Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript

即使有 CSS2 支持和 mootools(javascript 库),你也可以用这个 javascript 替换样式

<script type="text/javascript">
    // obviously this script line should go in a js file in a onload (or onDomReady) function
    $$('div.posts div:odd').setStyle('background-color','red');
</script>

If you don't have anything but php a it you can simplify a bit yous code using an array

如果你除了 php 什么都没有,你可以使用数组简化一点你的代码

<? $isodd=array('','odd');
   $c=0;
   foreach($posts as $post){?>
    <div class="<?=$isodd[$c++%2]?>">
        <?=$post?>
    </div>
<? }?>

回答by Hugh Bothwell

You can encapsulate the logic as follows:

您可以将逻辑封装如下:

<?php

class ListCycler {
    private $cols, $offs, $len;

    // expects two or more string parameters
    public function __construct() {
        $this->offs = -1;
        $this->len = func_num_args();
        $this->cols = func_get_args();

        foreach($this->cols as &$c)
            $c = trim(strval($c));
    }

    // the object auto-increments every time it is read
    public function __toString() {
        $this->offs = ($this->offs+1) % $this->len;
        return $this->cols[ $this->offs ];
    }
}
?>
<html>
<head>
  <style>
    ul#posts li.odd { background-color:red; }
    ul#posts li.even { background-color:white; }
  </style>
</head>
<body>
  <div>
    <h3>Posts:</h3>
    <ul id="posts"><?php
        $rc = new ListCycler('odd','even');
        foreach($posts as $p)
            echo "<li class='$rc'>$p</li>";
    ?></ul>
  </div>
</body>
</html>

回答by csl

On a side noe, to alternate between two values aand b, a nice way of doing it in a loop is this:

另一方面,要在两个值ab之间交替,在循环中执行此操作的一种好方法是:

x = a;
while ( true ) {
    x = a + b - x;
}

You can also do this without addition and subtraction:

您也可以在不加减法的情况下执行此操作:

x = a ^ b ^ x;

where ^is the XOR operation.

其中^是异或运算。

If you just want to alternate between 0 and 1, you can do this:

如果你只想在 0 和 1 之间交替,你可以这样做:

x = 0;
while ( true ) {
    x = !x;
}

You could of course use xas an index of colors, CSS style classes and so on.

您当然可以使用x作为颜色索引、CSS 样式类等。