Javascript jQuery查找最高父级TD

Javascript jQuery查找最高父级TD,javascript,jquery,html,Javascript,Jquery,Html,我正在为表中包含的表单编写代码。我正在(用jQuery)编写一个函数来突出显示每个元素的父。这一部分很简单-代码如下: $('.myForm input').click(function(){ $(this).parent().addClass('active'); }) 更复杂的部分是,一些文本字段位于嵌套在第一个表的中的第二个表的内部。它看起来像: <table> <tr> <td> <--cell I wa

我正在为表中包含的表单编写代码。我正在(用jQuery)编写一个函数来突出显示每个
元素的父
。这一部分很简单-代码如下:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })
更复杂的部分是,一些文本字段位于嵌套在第一个表的
中的第二个表的内部。它看起来像:

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


将类添加到一个函数中?

最好的解决方案是将一个类添加到您实际要针对的表中。这意味着您可以在将来更新标记,而不必破坏JS,方法是执行类似于
$(This).nexist('.targetElement').addClass('active')
的操作

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

$('.myForm input').click(function(){
    $(this).parents('td').last().addClass('active');
})
请参阅jQuery手册:

尝试这样做:

$('.myForm input').click(function(){
   $(this).parents('td').last().addClass('active');
})
我建议试试:

 $(this).parents("td").last()
它将查找当前元素的所有表单元格祖先。最后一个应包含最高级别的表格单元格元素。

您可以尝试:

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


为顶级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');
});

快脏:)


您的代码运行选择两次(不必要的开销),并执行与相同的操作。
$(this).parents('td:last');
$(this).parents('td').last();
<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');
});
$(this).parents('td')[--$(this).parents('td').length]