首页 > 解决方案 > 如何按照条件在表格中划线?

问题描述

我有一个问题,如何根据列数据在表格中加下划线。下面是示例编码来解释我面临的问题:

我想检测列underline是否为 1 名字数据将绘制下划线,如果 0 名字数据不显示下划线。下面的示例是硬代码,如果实际情况,我有太多行来显示数据,我不能一一添加text-decoration: underline;到 td 中。所以,希望有人能指导我如何解决这个问题。我正在使用 php 代码使变量定义下划线。


<!--Below the php code I just write the logic, because I don't know how to write to detect the column underline value-->
<?php
if ( <th>Underline</th> == 1) {
$add_underline = "text-decoration: underline;";
                                }
 if ( <th>Underline</th> == 0) {
$add_underline = "text-decoration: underline;";
                                }
?>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Underline</th>
  </tr>
  <tr>
    <td style="<?php echo $add_underline;?> ">Jill</td>
    <td>Smith</td>
    <td>1</td>
  </tr>
  <tr>
    <td style="<?php echo $add_underline;?>">Eve</td>
    <td>Jackson</td>
    <td>0</td>
  </tr>
  <tr>
    <td style="<?php echo $add_underline;?>">John</td>
    <td>Doe</td>
    <td>1</td>
  </tr>
</table>

我的输出如下图所示:

输出1

我的预期结果如下图所示,吉尔和约翰可以强调: 输出2

标签: phphtmlcss

解决方案


为什么不使用 javascript 来实现呢?无论服务器发送什么,它都会评估条件是否1已设置,然后相应地加下划线......您必须使用类来获取保存值的适当表数据标签,我添加class='name'到名称<td>标签和class='underline'下划线<td>标签。

// get the values of the elements with a class of 'name'
let names = document.getElementsByClassName('name');
// get the values of the elements with a class of 'underline'
let underline = document.getElementsByClassName('underline');
// loop over elements using for and use the keys to get and set values
// `i` will iterate until it reaches the length of the list of elements with class of underline
for(let i = 0; i < underline.length; i++){
  // use the key to get the text content and check if 1 is set use Number to change string to number for strict evaluation
  if(Number(underline[i].textContent) === 1){
      // set values set to 1 to underline in css style
      names[i].style.textDecoration = "underline";
  }
}
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Underline</th>
  </tr>
  <tr>
    <td class="name">Jill</td>
    <td>Smith</td>
    <td class='underline'>1</td>
  </tr>
  <tr>
    <td class="name">Eve</td>
    <td>Jackson</td>
    <td class='underline'>0</td>
  </tr>
  <tr>
    <td class="name">John</td>
    <td>Doe</td>
    <td class='underline'>1</td>
  </tr>
</table>

或使用 td 子值...

let tr = document.querySelectorAll("tr");
last = null;
for(let i = 1; i < tr.length; i++){
  if(Number(tr[i].lastElementChild.innerHTML) === 1){
      tr[i].firstElementChild.style.textDecoration = "underline";
  }
}
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Underline</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>1</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>0</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>1</td>
  </tr>
</table>


推荐阅读