获得< ul>的等级位置和< li>在jquery [英] Getting hierarchical positions of <ul> and <li> in jquery

查看:64
本文介绍了获得< ul>的等级位置和< li>在jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图让我的li使用jquery进行深度嵌套,然后创建一个包含li和数字的字符串,了解它们嵌套的深度。例如:

I'm trying to get how deeply nested my li's are using jquery, and then create a string containing the li's and numbers on how deeply they are nested. For example:

<ul>
    <li>
    MenuItem1
    </li>

    <li>
    MenuItem2
        <ul>
            <li>
            SubItemA
            </li>
        </ul>
    </li>

    <li>
    MenuItem3
    </li>
</ul>

应生成0:MenuItem1 0:MenuItem2 1:SubItemA 0:MenuItem3 或至少类似的东西。任何想法将不胜感激。

should produce "0:MenuItem1 0:MenuItem2 1:SubItemA 0:MenuItem3" or at least something similar like that. Any ideas will be appreciated.

推荐答案

类似于:

var text = $('li').map(function() {
     var num_parents = $(this).parents('ul').length;
     // or .parentsUntil('#someId', 'ul') if you have `$('#someID li')` above
     return (num_parents - 1) + ': ' + $(this).contents().map(function() {
         if(this.nodeType === 3) {
             return $.trim(this.nodeValue);
         }
         return null;
     }).get().join('');
}).get().join(' ');

DEMO

根据您的实际HTML结构,您还可以简化检索的文本li 元素到

Depending on your actual HTML structure, you can also simplify retrieving the text of a li element to

return (num_parents - 1) + ': ' + $.trim(this.firstChild);

如果文字紧跟开头< li> tag。

if the text directly follows the opening <li> tag.

或者如果每个 li 元素中都有其他标签(例如 span 或 div )并且您想要获取其内容,您可以克隆当前节点并删除所有 ul 后代:

Or if you have other tags inside each li element (like span or div) and you want to get their content as well, you can clone the current node and remove all ul descendants:

var text = $.trim($(this).clone().find('ul').remove().end().text());
return (num_parents - 1) + ': ' + text;

参考: map 父母 parentsUntil 内容 get

Reference: map, parents, parentsUntil, contents, get

这篇关于获得&lt; ul&gt;的等级位置和&lt; li&gt;在jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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