How to set alternate row color for an iterated table in php?

前端 未结 3 1786
广开言路
广开言路 2021-01-21 23:51

I am using PHP and I am iterating a table with a result array ... I want to add row color and alternate row color to it.... How to do so? Any suggestion...



        
相关标签:
3条回答
  • 2021-01-22 00:15

    To streamline your server code you could use javascript to highlight your rows and add mouse over/out handlers to the rows to do whatever you want.

    Very easy to do with jquery and many examples.

    0 讨论(0)
  • 2021-01-22 00:16
    <?php 
    include("BLL/index.php");
    $objBLL = new BLL();
    $result = $objBLL->SelectQuery();
    $ID = $i;
    $i = 1;
    ?>
    <table border="1" width="50%">
        <tr>
            <td>ID</td>
            <td>NAME</td>
            <td>DESCRIPTION</td>
        </tr>   
    
    <?php
     while ($row = mysql_fetch_assoc($result)) {
      if ($i % 2 != 0) {# An odd row 
        $rowColor = "orange"; 
        echo '<tr bgcolor="' . $rowColor . '"><td >' . $row["ID"] . '</td><td >' . $row["Name"] . '</td><td >' . $row["Description"] . '</td></tr>' . "\r\n";
        $i++;
      }else{  # An even row 
        $rowColor = "green";
        echo '<tr bgcolor="' . $rowColor . '"><td >' . $row["ID"] . '</td><td >' . $row["Name"] . '</td><td >' . $row["Description"] . '</td></tr>' . "\r\n";
        $i++;
      } 
    }
    ?>  
    </table>    
    
    0 讨论(0)
  • 2021-01-22 00:31

    Use modulo

    <?php foreach($rackData as $key => $row) { ?>
        <?php printf('<tr class="%s">', ($key % 2) ? 'odd' : 'even'); ?>
        // ...
    

    Then you can define CSS classes with the names .odd and .even and given them the background-color you want the rows to alternate with.

    With modern browsers (read: not IE 8 or lower) you can also do it directly in CSS with the :nth-child pseudo class:

    tr:nth-child(even) { background-color: #FFF; }
    tr:nth-child(odd) { background-color: #EEE; }
    
    0 讨论(0)
提交回复
热议问题