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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:22:34  来源:igfitidea点击:

Direct descendants only with jQuery's find()

javascriptjquerydom

提问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 ulelements, each with other ulelements inside them, and some root lielements too. I store a specific parent ulin a variable (as a jQuery object) and then look for any of the root lielements 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 lithat belongs to the ulinside the ul, if that makes sense.

但是,如果有意义的话,此方法还会查找li属于ul内部的任何内容ul

My question is, how can I select only direct descendants of type liwithin the my_root_ulobject using find(). Ordinarily, we could use something like $('ul > li')to return only direct lielements, 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');