jQuery找到最高的父TD

时间:2011-11-16 22:43:02

标签: javascript jquery html

我正在处理表格中包含的表单的代码。我正在编写(使用jQuery)一个函数来突出显示每个<td>元素的父<input>。这部分很简单 - 代码只是:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

更复杂的部分是某些文本字段位于嵌套在第一个表的<td>内的第二个表中。它看起来像是:

<table>
    <tr>
        <td> <--cell I want to add the class to
            <table>
                <tr>
                    <td><input type='text'></td>
                </tr>
            </table>
        </td>
     </tr>
</table>

所以我的问题是:有没有办法使用一个jQuery语句来查找<td>元素的最高父<input>?换句话说,我可以合并:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

$('.myForm input').click(function(){
    $(this).parent().parent().addClass('active');
    })

进入一个功能?

6 个答案:

答案 0 :(得分:20)

最好的解决方案是在您想要定位的表中添加一个类。这意味着您可以通过执行类似$(this).closest('.targetElement').addClass('active')的操作来更新标记,而不必破坏JS。

如果无法这样做,您可以使用parents('td').last()。这将选择所有td个父元素,然后获取最后一个元素。

$('.myForm input').click(function(){
    $(this).parents('td').last().addClass('active');
})

参见jQuery手册:

答案 1 :(得分:3)

尝试这样做:

$('.myForm input').click(function(){
   $(this).parents('td').last().addClass('active');
})

答案 2 :(得分:3)

我建议尝试:

 $(this).parents("td").last()

它将找到当前元素的所有表格单元格祖先。最后一个应该包含最高级别的表格单元格。

答案 3 :(得分:2)

你可以尝试:

$(this).parents('td:last');

$(this).parents('td').last();

答案 4 :(得分:1)

为您的顶级td元素添加一个类名:

<table>
    <tr>
        <td class="topTD"> <--cell I want to add the class to
            <table>
                <tr>
                    <td><input type='text'></td>
                </tr>
            </table>
        </td>
     </tr>
</table>


$('.myForm input').click(function(){
   $(this).closest('td.topTD').addClass('active');
});

答案 5 :(得分:0)

快速和肮脏:)

$(this).parents('td')[--$(this).parents('td').length]
相关问题