我正在尝试使用行的替代颜色方案在表格中显示数据。
我使用下面的代码显示结果。
<?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>
请指导
答案 0 :(得分:5)
使用css:
tr:nth-child(odd) {
background-color: #ccc;
}
这个小提示显示了如何选择even
,odd
,每个n'th
或每个n'th + x
行来设置样式,只需使用CSS:
答案 1 :(得分:0)
使用模运算符:
<?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> " ;
}
答案 2 :(得分:0)
尝试如下所示
<?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++;
}
?>
答案 3 :(得分:0)
使用计数器:
$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> " ;
}
答案 4 :(得分:0)
您需要使用modulus operator获取将$rowNum
除以2的余数。基本上,对于每一行,请向$rowNum
添加一行,然后检查它是否为username
偶数或奇数。另外,请确保为total
和<?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>";
}
?>
添加引号。由于您没有将它们包含在字符串中,因此它们被视为常量。
{{1}}
答案 5 :(得分:0)
您可以使用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> " ;
}
?>