我想向单击的th
元素和所有相应的td
元素添加一个类。单击另一个th
时,必须从td
和th
中删除该类。
我正在尝试将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 - 将类添加到单击的th和相应的td,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25390740/