2011-11-16 83 views
11

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

$('.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的一个语句找出最高父<input><td>的方法吗?因此,换句话说,我可以结合:

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

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

成一个功能?

回答

19

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

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

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

见jQuery的手册:

+0

+1比我快:-P –

3

尝试这样做:

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

我建议尝试:

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

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

2

你可以试试:

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

$(this).parents('td').last(); 
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'); 
}); 
0

快速&脏:)

$(this).parents('td')[--$(this).parents('td').length] 
+1

您的代码运行选择两次(不必要的开销)并执行与[.last()](http://api.jquery.com/last/)相同的操作。 – lsuarez