如何使用 jQuery 选择嵌套列表的叶元素

发布于 2024-12-26 00:21:03 字数 631 浏览 4 评论 0原文

我只需要选择嵌套列表的叶链接元素
示例 HTML

<ul>
    <li>folder
        <ul>
            <li>><a class="t-link" href="">folder</a>
                <ul>
                    <li><a class="t-link" href="">leaf 1</a><li>
                    <li><a class="t-link" href="">leaf 2</a><li>
                </ul>
            </li>            
        </ul>
    </li>
</ul>

因此,在此示例中,我想选择两个叶链接,但不选择文件夹链接 文件夹可以无限深度嵌套(但通常只有 2-3 层)。我想我需要寻找不包含 ul 元素的 li 元素,但我看不到你如何在 jQuery 中做到这一点

I need to select only the leaf link elements of a nested list
Sample HTML

<ul>
    <li>folder
        <ul>
            <li>><a class="t-link" href="">folder</a>
                <ul>
                    <li><a class="t-link" href="">leaf 1</a><li>
                    <li><a class="t-link" href="">leaf 2</a><li>
                </ul>
            </li>            
        </ul>
    </li>
</ul>

So in this example I want to select the two leaf links but not the folder link
The folders can be nested infinitely deeply (but typically only 2-3 levels). I figure I need to look for li elements that don't contain ul elements but I can't see how you do that in jQuery

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

婴鹅 2025-01-02 00:21:03

这将选择没有其他无序列表的叶节点作为子节点:

$("li:not(:has(ul))")

带有颜色编码示例的快速 jsFiddle: http://jsfiddle .net/rFuUc/

This will select the leaf nodes that do not have other unordered lists as children:

$("li:not(:has(ul))")

Quick jsFiddle with color coded example: http://jsfiddle.net/rFuUc/

一江春梦 2025-01-02 00:21:03
$('.t-link').parent().find(' ul .t-link')

应该有效。

$('.t-link').parent().find(' ul .t-link')

should work.

愛上了 2025-01-02 00:21:03

尝试

$('li').each(function(){
    if($(this).children('ul').size() == 0)
    {
        alert($(this).find('a').text());        
    }
});

DEMO

try

$('li').each(function(){
    if($(this).children('ul').size() == 0)
    {
        alert($(this).find('a').text());        
    }
});

DEMO

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文