jQuery只选择主表中的tr / td,而不是嵌套表。

我目前有一个带有嵌套表的表:

 <-- on click from this level only 
item1 item2
<-- not to be fired here

等表结构。

我目前正在使用以下jQuery,无论表级别如何,都会触发每个tr 。 如何将其更改为仅在第一级触发?

  $(document).ready(function(){ $("#report tr:not(.odd)").hide(); $("#report tr:first-child").show(); $("#report tr.odd").click(function(){ $(this).next("#report tr").fadeToggle(600); }); }); 

使用子选择器>仅选择那些作为报表tbody的子元素的tr元素,例如:

 $("#report > tbody > tr.odd") 

使用此解决方案,您之间是否有tbody标记无关紧要:

 $('table').find('tr:first').parent().children() 

您使用>选择器仅定位元素的直接后代。 您还必须在表中定位隐式tbody元素:

 $('#report>tbody>tr.odd') 

你要

 $("#report>tr") 

>表示直系后代(孩子)而不是任何后代。