繁体   English   中英

PHP while循环,返回偶数/奇数行

[英]PHP while loop, even/odd rows returned

我有一个PHP循环,显示我网站上特定帖子的数据。 我想要做的是为返回的行数动态分配任一和偶数/奇数CSS类。 例如,

first row returned - odd class
second row returned - even class
third row - odd class

这将允许我分配不同的背景颜色,以保持数据在视觉上分开。

我应该澄清 - 这些数据没有在表格中返回。

 while ($row = mysql_fetch_assoc($result)) {

    echo "
    <div class=\"songContainer\" id=\"" . $row['trackid'] . "\">

根据您必须定位的浏览器,您可以使用CSS执行此操作:

.mytable tr:nth-child(even) { background-color: #FFF; }
.mytable tr:nth-child(odd) { background-color: #EEE; }

你甚至可以用这个伪类做更复杂的事情: http//www.quirksmode.org/css/nthchild.html

如果你真的需要PHP,请使用模数:

$i = 0;
foreach ($arr as $val) {
    if (0 == $i % 2) {
        // even
    }
    else {
        // odd
    }
    $i++;
}

像这样在CSS3中支持nth-child类。

table tr:nth-child(even) td{

}

table tr:nth-child(odd) td{

}

但是如果你也支持旧版本,你别无选择,只能通过PHP生成类名。

使用php时,你可以使用它而不是Pascal建议的模数:

    $i = 0;
    foreach ($arr as $val) {
        if ( $i = 1 - $i ) {
            // even
        }
        else {
            // odd
        }
    }

使用这个jQuery:

$("tr:nth-child(2n)").addClass("even")
  .prev().addClass("odd");

它选择每隔二个tr元素并为其添加一个偶数类。 然后它选择前一个tr元素并为其添加一个奇数类。

例子

$num_rows = 0;
$current_class = "";
while ($row = mysql_fetch_array($result)){
    $current_class = "class_odd";
    if($num_rows % 2 == 0){
        $current_class = "class_even";
    }

    $num_rows++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM