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

时间:2010-03-04 16:32:03

标签: jquery

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

   <table class="datagrid" id="report">
       <thead>
         <tr>
          <th>item1</th>
          <th>item2</th>
         </tr>
       </thead>
       <tbody>
       <tr class="odd"> <-- on click from this level only 
        <td></td>  
        <td></td>
       </tr>
       <tr>
        <td colspan="2">
         <table>
          <tr class="odd"> <-- not to be fired here
           <td></td> 

等表结构。

我目前正在使用以下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);
            });
        });

4 个答案:

答案 0 :(得分:29)

使用child selector >仅选择报告tr的子元素tbody元素,例如:

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

答案 1 :(得分:10)

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

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

答案 2 :(得分:3)

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

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

答案 3 :(得分:0)

你想要

$("#report>tr")

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

相关问题