jQuery 只选择主表中的 tr/td,而不是嵌套表。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2380917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery select only tr/td in main table, not nested tables.
提问by TheAlbear
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);
});
});
回答by Gumbo
Use the child selector >
to only select those tr
elements that are a child of the reporttable's tbody
, for example:
使用子选择器>
仅选择tr
作为报告表的子元素的那些元素,tbody
例如:
$("#report > tbody > tr.odd")
回答by nerdess
with this solution it does not matter whether you have a tbody tag in between:
使用此解决方案,您之间是否有 tbody 标签并不重要:
$('table').find('tr:first').parent().children()
回答by Guffa
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')
回答by Keltex
You want
你要
$("#report>tr")
The >
means direct descendant (child) rather than any descendant.
该>
指直系后裔(孩子),而不是任何后代。