Rob*_*Cox 4 html jquery list html-lists
如何在无序列表中获得最深 li标记的深度?
例如,这个无序列表最深的li深度等于3:
<ul>
<li></li>
<li>
<ul>
<li></li>
</ul>
</li>
<li>
<ul>
<li>
<ul>
<li></li> <!-- I am the deepest -->
</ul>
</li>
</ul>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
Ion*_*zău 11
假设你没有选择器(id,class等),你需要一个没有ul的元素的简单循环.
// create maxDepth and cDepth variables
var maxDepth = -1
, cDepth = -1
;
// each `li` that hasn't `ul` children
$("li:not(:has(ul))").each(function() {
// get the current `li` depth
cDepth = $(this).parents("ul").length;
// it's greater than maxDepth found yet
if (cDepth > maxDepth) {
// this will become the max one
maxDepth = cDepth;
}
});
// alert
alert(maxDepth);
Run Code Online (Sandbox Code Playgroud)
如果你有.myClass最深的选择器li:
<ul>
<li></li>
<li>
<ul>
<li></li>
</ul>
</li>
<li>
<ul>
<li>
<ul>
<li class="myClass"></li>
</ul>
</li>
</ul>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这很简单:只计算其ul父母
var depth = $(".myClass").parents("ul").length;
Run Code Online (Sandbox Code Playgroud)