php - 如何按照条件在表格中划线?
问题描述
我有一个问题,如何根据列数据在表格中加下划线。下面是示例编码来解释我面临的问题:
我想检测列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>
我的输出如下图所示:
解决方案
为什么不使用 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>
推荐阅读
- c - 调用释放已存储值的 char 指针时,free() 函数失败
- mongodb - 使用 flask_MongoEngine 为 mongbd 设置 __id 的值
- led - 可见光传感器模块的制作方法
- swift - 为什么我不能在调用 func 时改变最初设置为某个参数的变量?
- javascript - 如何使用 jquery 在 Rails 6 中创建动态表单选择
- machine-learning - 线性回归测试数据违反训练数据。请解释我哪里出错了
- c# - Unity:如何将相机移动特定量?
- vue.js - 从 nuxt js 中的 localstorage 读取不是反应式的
- sql - 在 DB2 中更新十六进制值
- java - 尝试使用 Exchanger 通知线程已创建对象会导致两个线程都被锁定