问题描述
我正在试图让我的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(' ');
根据您的实际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;
参考: ,,,, get
Reference: map
, parents
, parentsUntil
, contents
, get
这篇关于获得< ul>的等级位置和< li>在jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!