我想向单击的th元素和所有相应的td元素添加一个类。单击另一个th时,必须从tdth中删除​​该类。

我正在尝试将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/

10-11 13:08