根据值更改表格行颜色

2024-03-27

我有一张看起来像这样的表:

ID     |     photo      |   ident     | status
------------------------------------------------
80     |    img/photo1  |   ACH3882   |   V
81     |    img/photo2  |   SHD8837   |   V
82     |    img/photo3  |   SFF4837   |   X
83     |    img/photo4  |   DLL3266   |   V

是否可以根据值更改行背景颜色?那么,如果状态单元格值为 V,则变为黄色,如果 X 变为绿色?

这是我的表,以及我尝试过的:

<table class="blueTable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" >
  <thead style= "background-color: #FFFFFF">
    <tr>
      <th>Photo</th>
      <th>Ident</th>
      <th>Status</th>
      <th>Delete</th>
    </tr>
  </thead>
  <tbody>
    <?php
     if ($result = $link->query($query)) {
          $num_rows = 0;
          while ($row = $result->fetch_assoc()) {
              $num_rows++;
                 if($row['status'] == 'V') {
                      $style = 'style="background-color:#00FF00;';
                  }
                  
                  if($row['status'] == 'X') {
                      $style = 'style="background-color:#FF00FF;';
                  }
              echo
              "<tr>
              <td>{$row['photo']}</td>
              <td>{$row['ident']}</td>
              <td>{$row['status']}</td>
              <td><a href='delete.php?id={$row['id']};'>Delete</a></td>
              </tr>";
             
          }
          /*freeresultset*/
          $result->free();
      }
    ?>
  </tbody>
</table>

但不知何故背景颜色没有改变。有什么建议么?


您可以使用状态变量作为类,并在 css 中添加类的颜色,如下所示

.color-v {
  background-color: blue;
}

.color-x {
  background-color: green;
}
<table class="blueTable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" >
  <thead style= "background-color: #FFFFFF">
    <tr>
      <th>Photo</th>
      <th>Ident</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <?php
     if ($result = $link->query($query)) {
          $num_rows = 0;
          while ($row = $result->fetch_assoc()) {
              $num_rows++;
              echo
              "<tr class='color-{$row['status']}'>
              <td>{$row['photo']}</td>
              <td>{$row['ident']}</td>
              <td>{$row['status']}</td>
              </tr>";
             
          }
          /*freeresultset*/
          $result->free();
      }
    ?>
  </tbody>
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据值更改表格行颜色 的相关文章