Jquery 将样式应用于表(当前列中的单元格除外)
我需要能够将样式应用于表中的所有单元格,当前列中的单元格除外 我正试图做这样的事情,但似乎不起作用。我错过了什么Jquery 将样式应用于表(当前列中的单元格除外),jquery,Jquery,我需要能够将样式应用于表中的所有单元格,当前列中的单元格除外 我正试图做这样的事情,但似乎不起作用。我错过了什么 var col = $(this).parent().children().index($(this)); $("#myTable td:nth-child(:not(col-1))").addClass("myClass"); <table id="myTable"> <tr> <td>col 1
var col = $(this).parent().children().index($(this));
$("#myTable td:nth-child(:not(col-1))").addClass("myClass");
<table id="myTable">
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
<tr>
<td><span class="click">click</span></td>
<td><span class="click">click</span></td>
</tr>
</table>
var col=$(this).parent().children().index($(this));
$(“#myTable td:n子项(:not(col-1))”).addClass(“myClass”);
第1列
第2列
点击
点击
由于col
是一个变量,因此必须使用字符串连接。您还需要将:not
放在前面
var col = $(this).parent().children().index($(this))-1;
$("#myTable td:not(:nth-child("+col+"))").addClass("myClass");
var col=$(this.parent().children().index($(this))-1;
$(“#myTable td:not(:n个子(“+col+”)).addClass(“myClass”);
下面是一个演示:
这将从所有TD元素中删除自定义类,然后将其添加到不在单击跨度的列中的元素中。请注意,如果对元素调用.index()
,将根据其同级元素获取该元素的索引
//bind click event handler to the `.click` elements
$('#myTable').find('.click').on('click', function () {
//remove class from all TDs
$('#myTable').find('td').removeClass('myClass');
//get the index of the clicked element based on its parents siblings
var index = $(this).closest('td').index();
//iterate though each TD element in the table and add the class to it if it isn't the same index as the clicked element
$.each($('#myTable').find('tr').children(), function () {
if ($(this).index() != index) {
$(this).addClass('myClass');
}
});
});