直接后代只有jQuery的find() [英] Direct descendants only with jQuery's find()

查看:124
本文介绍了直接后代只有jQuery的find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用jQuery的 find() children()函数选择元素的直接后代?

Is it possible to select only direct descendants of an element using jQuery's find() or children() functions?

我有几个 ul 元素,每个都有其他 ul 元素,还有一些根 li 元素。我在一个变量(作为一个jQuery对象)中存储一个特定的父 ul ,然后查找任何根​​ li 使用中的元素: my_root_ul.find('li');

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 li c $ c>里面的 ul ,如果这是有道理的。

However, this method also finds any li that belongs to the ul inside the ul, if that makes sense.

我的问题是,我该怎么选择使用 find() my_root_ul 对象内的 li 类型的直接后代C>。通常,我们可以使用 $('ul> li')之类的东西只返回直接 li 元素,必须可以过滤掉返回的元素?

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?

这是一个示例来说明我的意思:

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>


推荐答案

像这样:

my_root_ul.find('> li');

.children()还只选择直接的孩子,所以你也可以使用它:

.children() also selects only the immediate children, so you can use that also:

my_root_ul.children('li');

这篇关于直接后代只有jQuery的find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆