jquery:根据另一列的属性在一个表列上更新css

问题描述 投票:0回答:2

这是我的HTML表格

<!DOCTYPE html>
<html>
<body>
<table>
<thead>
<th>Header1</th>
<th>Header2</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id=0 /></td>
<td>TEXT1</td>
</tr>
<tr>
<td><input type="checkbox" id=1 checked/></td>
<td>TEXT2</td>
</tr>
</tbody>
</table>

</body>
</html>

please click here

我的目标是扫描表中的所有行(在页面加载后)并通过jquery更新第二列文本的css(显示在链接中)

例如,上面的表格应该如上所示(TEXT2元素通过)

我相信我们可以使用jquery css方法设置元素的css,如下所示

.css("text-decoration", "line-through")

但我迷失了如何构建一个jquery片段,可以扫描表中的所有行并执行css。

这在jquery中真的可行吗?

任何帮助表示赞赏!

javascript jquery html css
2个回答
2
投票

1.初始化脚本

要在页面加载后运行脚本,请考虑将.on()方法与load事件一起使用。

参考:.on() | jQuery API Documentation

2.迭代指定的元素:

要遍历所需的元素,请考虑将.each()方法与指定的css选择器td > input一起使用,以直接定位input元素的嵌套td元素(从而绕过碰巧嵌套在任何特定input元素中的所有td元素的目标,以及否定需要链接另一个.find()方法来指定所需的嵌套元素)。

参考:.each() | jQuery API Documentation

3.检查所需条件:

要验证相关元素是否具有checked属性,请考虑使用条件语句(如if())来检查条件是否计算为true。 如果是,请在条件语句块中使用.css()方法添加所需的内联样式。

参考:.css() | jQuery API Documentation

代码片段演示:

$(window).on('load', function(){
  
  $('td > input').each(function(){
    if($(this).attr('checked')) {
      $(this).parent().next().css('text-decoration', 'line-through');
    }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th>Header1</th>
    <th>Header2</th>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" id="text0" /></td>
      <td>TEXT1</td>
    </tr>
    <tr>
      <td><input type="checkbox" id="text1" checked/></td>
      <td>TEXT2</td>
    </tr>
  </tbody>
</table>

注意:

  1. 如果值以整数(数字/单位值)开头,则id选择器无效,例如:id="0",该值必须以字符串开头,例如:id="text0"
  2. 用撇号包裹属性值,例如:id="text0"

0
投票

我是在Jquery做到的:

在选中复选框的第二列上删除文本。

但还包括要删除第二列上的文本是用户用户点击复选框

$(document).ready(function(){
 $('input:checkbox').on('change', function () {
        var inpt = $(this).parent().next('td');
        if (this.checked) {
           
            $(inpt).css('textDecoration', 'line-through');
        } else {
            $(inpt).css('textDecoration', 'none');
        }
    });
  var i=   $('input[type=checkbox]:checked').parent().next('td');
  if ($('input[type=checkbox]:checked')) {
           
            $(i).css('textDecoration', 'line-through');
            }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<table>
<thead>
<th>Header1</th>
<th>Header2</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id=0 /></td>
<td>TEXT1</td>
</tr>
<tr>
<td><input type="checkbox" id=1 checked/></td>
<td>TEXT2</td>
</tr>
</tbody>
</table>

</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.