jQuery 如何通过jQuery函数仅获取直接子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3687637/
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
How to get only direct child elements by jQuery function
提问by Jason Li
I have a table structure like this:
我有一个这样的表结构:
<table1>
<tbody>
<tr>
<td></td>
...
<td>
<table2>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
In javascript, I have a variable tbl
with value of $(table1)
, and then I want to get all direct child elements (tr) of <tbody>
of table1
.
My code is :
在JavaScript中,我有一个变量tbl
与价值$(table1)
,然后我想获得的所有直接子元素(TR)<tbody>
的table1
。我的代码是:
$('tr', tb1)
Apparently it returns all <tr>
elements in table1 and table2.
I think I can get by
显然它返回<tr>
table1 和 table2 中的所有元素。我想我能熬过去
$('tr', tb1).not(function(){return $(this).parent().parent()[0] != tb1;})
or this kind of logic.
或者这种逻辑。
I know $('table1 > tbody > tr')
can get the direct child tr
. Unfortunately I can not use this.
我知道$('table1 > tbody > tr')
可以直接拿到孩子tr
。不幸的是我不能使用这个。
Anyone has good idea about this?
有人对此有什么好主意吗?
Thanks.
谢谢。
回答by Chris
As @jave.web mentioned in the comments
正如评论中提到的@jave.web
To search through the direct children of an element use .children()
. It will only search through the direct children and not traverse any deeper. http://api.jquery.com/children/
要搜索元素的直接子元素,请使用.children()
. 它只会搜索直接的孩子,而不会遍历任何更深的孩子。http://api.jquery.com/children/
回答by ?ime Vidas
This is exactly the reason why one should be careful with nesting tables. I really hope that you use them for data and not page layout.
这正是人们应该小心嵌套表的原因。我真的希望您将它们用于数据而不是页面布局。
Another issue that will probably ruin your day is using CSS selectors on nested tables... you basically have the same issue - you are unable to select TR elements of the outer table without selecting those inside the inner table, too. (You cannot use the child selector because it is not implemented in IE6)
另一个可能会毁了你一天的问题是在嵌套表上使用 CSS 选择器......你基本上有同样的问题 - 你无法选择外部表的 TR 元素而不选择内部表中的元素。(您不能使用子选择器,因为它没有在 IE6 中实现)
This should work:
这应该有效:
$("#table1 > tbody > tr")
However, I recommend that you hardcode the TBODY element, since you should not rely on the browser to create it for you.
但是,我建议您对 TBODY 元素进行硬编码,因为您不应依赖浏览器为您创建它。
回答by Jeremy
http://api.jquery.com/child-selector/
http://api.jquery.com/child-selector/
$('tb1 > tr')
$('tb1 > tr')
回答by Ahmed Bilal
If you have ids of both elements and you want to find direct element use below code
如果你有两个元素的 id 并且你想找到直接元素使用下面的代码
$("#parent > #two")
If you want a nested search you can use find. It is explained in detail here. https://handyopinion.com/jquery-selector-find-nested-child-elements/
如果您想要嵌套搜索,可以使用 find。在这里详细解释。 https://handyopinion.com/jquery-selector-find-nested-child-elements/