javascript - 如何仅根据标题行应用一些 jquery 内容

标签 javascript jquery html-table jquery-selectors

我有这样的表格:

<table> 
<thead>
   <th>id </th><th>name </th><th>number </th><th>result </th> 
</thead>        
<tbody>
<tr>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td> 
</tr>
</tbody>
 </table>

我只想将 class = "red" 添加到那些 header 为 resulttd

所以只有在页面加载时动态使用 jquery 结果列。

最佳答案

您可以使用 .index() 获取 header 的索引然后使用 :nth-child selector 应用该类.

jsFiddle

enter image description here

var resultHeaderIndex = $('th:contains("result")').index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

如果您也想将类添加到 header ,那么您只需在获取索引之前添加它即可:

jsFiddle

enter image description here

var resultHeaderIndex = $('th:contains("result")')
    .addClass('red')
    .index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

关于javascript - 如何仅根据标题行应用一些 jquery 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15651408/

相关文章:

html - 如何将表格中的图像对齐到一行或其他内容的右侧?

javascript - 如何使用下一个和上一个按钮在表格之间切换?

javascript - Angular 7 - 为动态创建的组件添加拖放行为

javascript - 更改 <p> 值 onclick 不起作用

javascript - 在 React 中刷新页面后持久登录数据

Javascript - 检查 key 是否存在 - 如果不创建它,全部在一行中

javascript - JQuery slider 不能正常用于下一张幻灯片(.next() 有错误)

jquery - 透明背景iframe

javascript - 如何使用 javascript 和 tampermonkey 跨域发送数据?

angularjs - 在表格 Angular 中正确显示 JSON