Bootstrap在动态创建的表中交替行颜色

时间:2017-02-23 15:17:46

标签: php css twitter-bootstrap html-table

查看Stack Overflow,我找到了alternating row color。 虽然这似乎适用于静态表,但我的结果是所有行都是粉红色的。我无法让它在带有bootstrap的PHP动态创建表上工作:

$mdbFile = "\myAccessDatabase.mdb";
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$mdbFile", "", "");
$query = $pdo->prepare("SELECT * FROM Table");  
$query->execute();

echo "<table class='table table-striped table-bordered table-hover table-condensed table-responsive'>";                 
echo "<thead><tr>";
echo "<th>Last</th><th>First</th><th>XXX</th><th>YYY</th><th>ZZZ</th><th>WWW</th>";
echo "</tr></thead>";

for($i=0; $row = $query->fetch(); $i++){
    echo '<tbody><tr>';
    //echo "<th scope='row'>1</th>";
    echo "<td>".$row['LAST']."</td>";
    echo "<td>".$row['FIRST']."</td>";
    echo "<td>".$row['XXX']."</td>";
    echo "<td>".$row['YYY']."</td>";
    echo "<td>".$row['ZZZ']."</td>";
    echo "<td>".$row['WWW']."</td>";
}
echo "</tr></tbody></table>"; 

unset($pdo);
unset($query);

CSS:

.table-striped>tbody>tr:nth-child(odd)>td,
    .table-striped>tbody>tr:nth-child(odd)>th {
        background-color: pink;
    }

2 个答案:

答案 0 :(得分:3)

问题可能是您的开始tbody标记位于循环内。所以每一行都被视为第一行。试着把它带到外面:

 echo '<tbody>';
for($i=0; $row = $query->fetch(); $i++){
    echo '<tr>';
    //echo "<th scope='row'>1</th>";
    echo "<td>".$row['LAST']."</td>";
    echo "<td>".$row['FIRST']."</td>";
    echo "<td>".$row['XXX']."</td>";
    echo "<td>".$row['YYY']."</td>";
    echo "<td>".$row['ZZZ']."</td>";
    echo "<td>".$row['WWW']."</td>";
    echo '</tr>';
  }
    echo "</tbody></table>"; 

答案 1 :(得分:0)

试试这个.table-striped>tbody>tr:nth-of-type(odd) { background-color: pink; }