javascript - 添加class到clicked th和对应的td

标签 javascript jquery html-table

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

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

相关文章:

javascript - 无法覆盖 JS 函数

jquery - 当 DIV 进入 View 时添加类

javascript - 如何用灰色标记 html 范围 slider (已选择的所有区域)?

php - 如何在 mysql 和 PHP 中将每个数据添加到表的列中?

javascript - 硬表行交换,交换行的父级为空

jquery - 如何使用 jQuery 克隆表中的两列

javascript - 如何将引导按钮与输入复选框链接起来?

javascript - ng-repeat 中一次绑定(bind)后的 AngularJS 过滤器

javascript - Angular 服务在 spyOn 时变得未定义

java - 如何从 Android webview 中加载的 HTML 中获取 DOM 的内容?