![](/img/trans.png)
[英]How to give alternating table rows different background colors in while loop and CSS (not using :nth-child() selector)
[英]How to give alternating table rows different background colors using PHP
我有一個根據存儲在 mysql 數據庫中的內容動態生成的數據表。
這是我的代碼的樣子:
<table border="1">
<tr>
<th>Name</th>
<th>Description</th>
<th>URL</th>
</tr>
<?php
$query = mysql_query("SELECT * FROM categories");
while ($row = mysql_fetch_assoc($query)) {
$catName = $row['name'];
$catDes = $row['description'];
$catUrl = $row['url'];
echo "<tr class=''>";
echo "<td>$catName</td>";
echo "<td>$catDes</td>";
echo "<td>$catUrl</td>";
echo "</tr>";
}
?>
</table>
現在,如果表格是靜態的,那么我只需按重復順序為每個交替表格行指定 2 種樣式之一:
.whiteBackground { background-color: #fff; }
.grayBackground { background-color: #ccc; }
那將是結束。 但是,由於表行是動態生成的,我該如何實現呢?
或者你可以只使用 CSS:
table tr:nth-child(odd) { background-color: #ccc; }
<?php
$x++;
$class = ($x%2 == 0)? 'whiteBackground': 'grayBackground';
echo "<tr class='$class'>";
?>
它基本上檢查 $x 是否可以被 2 整除。如果是,它是偶數。
PS 如果您還沒有看到 if else 查詢的那種風格,它被稱為三元運算符。
<?
$color="1";
while ($line = mysql_fetch_array($result)) {
if($color==1){
echo '<tr bgcolor="">';
$color="2";
} else {
echo '<tr bgcolor="#dcdcdc">';
$color="1";
}
?><td align="left" width="40"><a href=""></a><?= $line[name] ?></td>
<?
}
?>
這是我的工作代碼!
這是我的工作部分! `
$i=1;
while($row = mysqli_fetch_array($result)) {
if($i%2==0)
{
echo '<tr bgcolor="#FFFF00">';
}
else
{
echo '<tr bgcolor="#99FFCC">';
}
$i++;
echo "<td>" . $row['blah'] . "</td>";
echo "<td>" . $row['blah_blah'] . "</td>";
echo "</tr>";
}
echo "</table>";
`
將變量設置為 true/false 或一個數字,然后在每次迭代期間再次返回。 或者在 $i 是一個數字的 while 循環中使用模數運算符,例如 $i%2==0 並在三元語句或設置<tr>
的類值的東西中使用此條件
$i = 0;
while ( $row = mysql_fetch_assoc($result) ) {
echo '<tr class="' . ( ( $i %2 == 0 ) ? 'oneValue' : 'anotherValue' ) . '"><td>' . $row['something'] . '</td></tr>';
$i++;
}
我就是這樣做的。 我用我想要的所有樣式聲明了一個名為“even”的css類。 然后循環遍歷場景。 希望能幫助到你!
<?php
include 'connect.php';
echo "<table id='hor-zebra'>";
$i = 0;
while($row = mysql_fetch_array($result))
{
if($i%2 == 0)
{
echo "<tr class='even'>";
echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
echo "</tr>";
}
$i++;
}
echo "</table>";
mysql_close($con);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.