Given the following table, how would I get the corresponding table header for each td element?

<table>
    <thead> 
        <tr>
            <th id="name">Name</th>
            <th id="address">Address</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td>Bob</td>
            <td>1 High Street</td>
        </tr>
    </tbody>
</table>

Given that I currently have any of the td elements available to me already, how could I find the corresponding th element?

var $td = IveGotThisCovered();
var $th = GetTableHeader($td);

推荐答案

var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');

还是简化一点

var $th = $td.closest('table').find('th').eq($td.index());

Jquery相关问答推荐

JQuery日期 Select 器未设置从jQuery中 Select 的月份起90天或3个月

使用jquery ui来回滑动切换

为什么我不能在 window.onload 事件的处理程序中将 $ jQuery 对象作为参数传递?

如何使用 aria-expanded="true" 更改 CSS 属性

禁用提交按钮,直到所有字段都有值

输入类型=文件的jQuery更改方法

jquery清除输入默认值

如何使用 jQuery 清空输入值?

jQuery 插入 div 作为某个索引

jQuery 序列化不注册复选框

在没有 jQuery 的情况下在 node.js 上合并或合并 JSON

jQuery 对象和 DOM 元素

如何获取 onclick 调用对象?

Select 除第一个之外的所有子元素

jQuery Force 为 iframe 设置 src 属性

更改 Eclipse 设置以忽略特定文件上的错误

JQuery - 按值查找单选按钮

在jQuery中获取CSS规则的百分比值

如果一个元素正在被动画,我如何用 jQuery 找出?

获取jQuery中下拉列表的值