繁体   English   中英

如何在具有交替行颜色的表中显示数据

[英]how to display data in tables with alternate row colour

我正在尝试使用行的替代颜色方案在表中显示数据。

我正在使用下面的代码显示结果。

<?php 


      while($row = mysql_fetch_array($sql))  {
          echo "<tr> ";
           echo "<td>" .$row[username] . "</td>";
         echo "<td>" .$row[total] . "</td>";
         echo "</tr> " ;
}

?>

我想使用这种格式来显示数据:

<tbody>
<tr class="alt"><td>Data</td><td>points</td></tr>
<tr><td>Data</td><td>points</td></tr>
<tr class="alt"><td>Data</td><td>points</td></tr>
<tr><td>Data</td><td>points</td></tr>
<tr class="alt"><td>Data</td><td>point</td></tr>

</tbody>

请指导

使用CSS:

tr:nth-child(odd) {
   background-color: #ccc;
}

这个小提琴展示了如何仅使用CSS选择evenodd ,第n'th或第n'th + x行来设置其样式:

http://jsfiddle.net/zhd66arb/1/

使用模运算符:

<?php
  $rowNum=0; 
  while($row = mysql_fetch_array($sql))  {
      echo "<tr ";
      if ($rowNum++ % 2 == 0) {
          echo 'class="alt"';
      }
       echo " >";
       echo "<td>" .$row[username] . "</td>";
     echo "<td>" .$row[total] . "</td>";
     echo "</tr> " ;
  }

尝试如下所示

<?php 

      $i = 0;
      while($row = mysql_fetch_array($sql))  {
      $class = "";
      if($i % 2 == 0)
          $class = "class='alt'";
      echo "<tr $class> ";
         echo "<td>" .$row[username] . "</td>";
         echo "<td>" .$row[total] . "</td>";
      echo "</tr> " ;
      $i++;
}

?>

使用计数器:

$i = 1
while($row = mysql_fetch_array($sql))
{
    echo "<tr" . (($i++%2) ? '' : ' class="alt"') . ">";
    echo "<td>" .$row[username] . "</td>";
    echo "<td>" .$row[total] . "</td>";
    echo "</tr> " ;
}

您将需要使用模运算符来获得将$rowNum除以2的余数。基本上,对于每一行,在$rowNum添加一个,然后检查它是偶数还是奇数。 另外,请确保将引号添加到usernametotal 由于您没有将它们括在字符串中,因此它们被视为常量。

<?php
$rowNum = 0;

while($row = mysql_fetch_array($sql))  {
    echo ($rowNum++ % 2 == 0) ? "<tr class=\"alt\">" : "<tr>";
    echo "<td>" .$row['username'] . "</td>";
    echo "<td>" .$row['total'] . "</td>";
    echo "</tr>";
}
?>

您可以使用count变量对循环进行计数,然后使用count%2进行其他所有迭代。

<?php 

  $count = 0;  //The count variable
  while($row = mysql_fetch_array($sql))  {

     echo "<tr" // open the tag

       if($count%2 == 0) {
          echo "class='alt'"; // Ever other iteration, this will run
       }

     echo ">"; // close the tag
     echo "<td>" .$row[username] . "</td>";
     echo "<td>" .$row[total] . "</td>";
     echo "</tr> " ;
}

?>

暂无
暂无

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

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