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

时间:2022-05-24 15:27:02

I currently have a table with a nested table in it:

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

   <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> 

etc table structure.

等表结构。

I am currently using the following jQuery, which fires on every tr regardless of the table level. How do I change it to only fire on the first level?

我目前正在使用以下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 个解决方案

#1


29  

Use the child selector > to only select those tr elements that are a child of the report table’s tbody, for example:

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

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

#2


9  

with this solution it does not matter whether you have a tbody tag in between:

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

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

#3


3  

You use the > selector to target only the direct descendant of an element. You have to target the implicit tbody element inside the table also:

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

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

#4


0  

You want

$("#report>tr")

The > means direct descendant (child) rather than any descendant.

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

#1


29  

Use the child selector > to only select those tr elements that are a child of the report table’s tbody, for example:

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

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

#2


9  

with this solution it does not matter whether you have a tbody tag in between:

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

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

#3


3  

You use the > selector to target only the direct descendant of an element. You have to target the implicit tbody element inside the table also:

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

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

#4


0  

You want

$("#report>tr")

The > means direct descendant (child) rather than any descendant.

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