【问题标题】:How to get the largest size of nested lists with jQuery如何使用 jQuery 获得最大尺寸的嵌套列表
【发布时间】:2012-07-17 16:58:49
【问题描述】:

这是我的问题:我有嵌套列表,并且我想获取最大列表的大小而不获取其子级。例如:

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

所以它会拉 5(主列表,或 4 假设索引 0),而不是 11 或其他。想法?我试图弄乱 size() 函数,但它也抓住了孩子们。

【问题讨论】:

    标签: jquery nested-lists


    【解决方案1】:
    $('ul').each(function() {
        console.log($('> li', this).length);
    });​
    

    返回 5、2、4。

    【讨论】:

      【解决方案2】:
      var items = $("ul > li");  //looks at all direct children of ul.
      var len = items.length; // the length will count the number of occurances of li appear.
      

      然后您可以分配一个全局变量来跟踪长度。

      if (GLOBAL < len){
         GLOBAL = items.parent();
      }
      

      设置全局 = 最大 LI 集的父级

      【讨论】:

      • 我认为这并不像您认为的那样有效。 items.parent() 将简单地返回一个包含每个 &lt;ul&gt; 的 jQuery 集合。在 OP 的示例标记中,GLOBAL 将设置为包含所有 3 个 &lt;ul&gt; 元素的集合。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多