【问题标题】:PHP while loop, even/odd rows returnedPHP while循环,返回偶数/奇数行
【发布时间】:2011-12-31 21:52:32
【问题描述】:

我有一个 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'] . "\">

【问题讨论】:

  • 您的问题是什么?你都尝试了些什么?请发布一些代码。请使用网站的搜索功能(因为这看起来像是一个重复的问题)。
  • 更快地拥有像 datatables.com 这样的前端 jquery 代码 - google jquery table display plugin

标签: php jquery css


【解决方案1】:

这样的 CSS3 支持 nth-child 类。

table tr:nth-child(even) td{

}

table tr:nth-child(odd) td{

}

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

【讨论】:

    【解决方案2】:

    根据您必须定位的浏览器,您可以使用 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++;
    }
    

    【讨论】:

      【解决方案3】:

      使用这个 jQuery:

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

      它每秒选择一次tr 元素并为其添加一个偶数类。然后它选择之前的tr 元素并为其添加一个奇数类。

      Example.

      【讨论】:

        【解决方案4】:
        $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++;
        }
        

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-11-27
            • 2013-12-20
            • 1970-01-01
            • 1970-01-01
            • 2012-10-10
            • 2012-05-30
            • 1970-01-01
            相关资源
            最近更新 更多