javascript 仅使用 jQuery 的 find() 直接后代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8415003/
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
Direct descendants only with jQuery's find()
提问by BenM
Is it possible to select only direct descendants of an element using jQuery's find()
or children()
functions?
是否可以使用 jQueryfind()
或children()
函数仅选择元素的直接后代?
I have several ul
elements, each with other ul
elements inside them, and some root li
elements too. I store a specific parent ul
in a variable (as a jQuery object) and then look for any of the root li
elements within using: my_root_ul.find('li');
.
我有几个ul
元素,每个ul
元素里面都有其他元素,还有一些根li
元素。我将一个特定的父元素存储ul
在一个变量中(作为一个 jQuery 对象),然后li
在 using: 中查找任何根元素my_root_ul.find('li');
。
However, this method also finds any li
that belongs to the ul
inside the ul
, if that makes sense.
但是,如果有意义的话,此方法还会查找li
属于ul
内部的任何内容ul
。
My question is, how can I select only direct descendants of type li
within the my_root_ul
object using find()
. Ordinarily, we could use something like $('ul > li')
to return only direct li
elements, but it must be possible to filter down the returned elements?
我的问题是,我怎么能选择类型的唯一的直接后裔li
的范围内my_root_ul
使用对象find()
。通常,我们可以使用 like$('ul > li')
只返回直接li
元素,但必须可以过滤掉返回的元素吗?
Here is an example to demonstrate what I mean:
这是一个示例来说明我的意思:
<ul>
<li>I want this
<ul>
<li>I don't want this</li>
<li>I don't want this</li>
<li>I don't want this</li>
</ul>
</li>
<li>I want this</li>
<li>I want this</li>
</ul>
回答by Tatu Ulmanen
Like this:
像这样:
my_root_ul.find('> li');
.children()
also selects only the immediate children, so you can use that also:
.children()
也只选择直接的孩子,所以你也可以使用它:
my_root_ul.children('li');