我想向单击的第 th
元素和所有相应的 td
元素添加一个类。单击另一个 th
时,必须从 th
和 td
中删除该类。
我正在尝试将第 th
的索引与 td
进行匹配:
$('th').click(function () {
var indexOf = $(this).index();
$('.sortable').removeClass('sortable');
$(this).addClass('sortable');
$('td:nth-child('+indexOf+')').addClass('sortable');
});
虚拟 HTML
<table class="data">
<tr>
<th>Entry Header 1</th>
<th>Entry Header 2</th>
<th>Entry Header 3</th>
<th>Entry Header 4</th>
</tr>
<tr>
<td>Entry First Line 1</td>
<td>Entry First Line 2</td>
<td>Entry First Line 3</td>
<td>Entry First Line 4</td>
</tr>
<tr>
<td>Entry Line 1</td>
<td>Entry Line 2</td>
<td>Entry Line 3</td>
<td>Entry Line 4</td>
</tr>
<tr>
<td>Entry Last Line 1</td>
<td>Entry Last Line 2</td>
<td>Entry Last Line 3</td>
<td>Entry Last Line 4</td>
</tr>
</table>
最佳答案
这应该可以做到:
$('th').click(function () {
var indexOf = $(this).index();
$('th,td').not('td:nth-child(' + (indexOf + 1) + '), th:nth-child(' + (indexOf + 1) + ')').removeClass('sortable')
$(this).add('td:nth-child(' + (indexOf + 1) + ')').toggleClass('sortable');
});
<强> jsFiddle example
关于javascript - 添加class到clicked th和对应的td,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390740/