我将MySQL数据库结果插入HTML表,之后我尝试使用两种颜色更改行颜色,
例如,如果第一行有红色,第二行又有黄色,第三行有红色就像智慧。。
最好的方法是什么?我使用PHP modulus函数编写了PHP代码,有什么最简单的方法吗?谢谢。。
<?php
$result = mysqli_query($link, "SELECT * FROM example");
?>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<?php
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
if ($i % 2 == 0) {
$bgColor = ' style="background-color:#CCFFFF;" ';
} else {
$bgColor = ' style="background-color:#FFFF99;" ';
}
echo "<tr>";
echo "<td $bgColor>";
echo $row['name'];
echo "</td>";
echo "<td $bgColor>";
echo $row['age'];
echo "</td>";
echo "</tr>";
$i++;
}
?>
</table>
可以通过CSS 完成
tr:nth-child(even) {background: yellow}
tr:nth-child(odd) {background: red}
来源:http://www.w3.org/Style/Examples/007/evenodd.en.html
包含css
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
用替换表格标签
<table class="table table-striped" >
您应该使用类.red和.ellow.而不是内联样式
<?php
$result = mysqli_query($link, 'SELECT * FROM example');
?>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<?php
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr class="' . (($i % 2 == 0) ? 'red' : 'yellow') . '">';
echo '<td>';
echo $row['name'];
echo '</td>';
echo '<td>';
echo $row['age'];
echo '</td>';
echo '</tr>';
$i++;
}
?>
</table>
您可以完全不使用PHP。只需将CSS与:nth子类伪类一起使用
tr:nth-child(2n) {
background: #f0f0f0; /* row background color */
}
tr:nth-child(1) {
background: #666; /* row background color */
color: #fff; /* text color */
}
顺便说一句,在接口中显示数据是一种非常糟糕的方式,将数据从数据库中获取并显示在视图中(放入输出缓冲区)。这段代码看起来像是PHP3的一本丑陋血腥的旧书中的一个转换示例片段。需要将两个过程分开:首先从DB中获取所有数据,然后将其放入具有外观的输出中。