计算无序列表的深度

4

如何获取无序列表中最深的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>
2个回答

12
假设您没有选择器(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);

JSFIDDLE

如果你有一个最深的li选择器的.myClass:

<ul>
  <li></li>
  <li>
    <ul>
      <li></li>
    </ul>
  </li>
  <li>
    <ul>
      <li>
        <ul>
          <li class="myClass"></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

很简单:只需计算其ul父级的数量。
var depth = $(".myClass").parents("ul").length;

jsfiddle中的示例有效。我无法在最深层上放置一个类,因为它将是一个动态创建的列表。谢谢! - Robin Cox
@RascalCapac 不用谢。我添加了第二个版本,以确保您知道它。如果您不知道哪个元素是最深的,只有循环才能为您完成。 :-) - Ionică Bizău
@RascalCapac :-) 我很高兴能在 StackOverflow 上帮助用户。来自罗马尼亚的最好的问候。 :-) - Ionică Bizău
你说得并不简单。能否请您解释一下? - Bhojendra Rauniyar
@C-link 我添加了内联注释。我猜这很简单。 :-) - Ionică Bizău
显示剩余2条评论

1
你可以使用类似的代码。
var parent = $('ul').children(),
child = parent;

while (child.length) {
parent = child;
child = child.children();
}

alert(parent.html());

演示

Html

<ul >
<li></li>
<li>
  <ul>
  <li></li>
 </ul>
</li>
<li>
<ul>
  <li>
    <ul>
      <li> I am the deepest </li> 
    </ul>
  </li>
 </ul>
  </li>
 </ul>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接