【问题标题】:Split ul to more ul's with jQuery使用 jQuery 将 ul 拆分为更多 ul
【发布时间】:2012-05-08 14:45:11
【问题描述】:

我用 jQuery 制作了一个脚本。该脚本将 li 列表拆分为更多 ul 列表。当列表超过 10 li 项时,必须将列表拆分为更多 ul。 我已经在这篇文章中制作了脚本。

但是脚本不工作。我在这里做错了什么。 该脚本用于导航中的子菜单。当导航li项大于4时,li项的ul必须拆分成两个ul。我该如何修复这个脚本。谢谢!

submenu();
function submenu() {
    $(".submenu").each(function () {
        if($("li", this).length > 4){
            $(this).closest(".submenu").addClass("width-2")

            var submenu = $(this).closest(".submenu");
            var $bigList = $(this), group;

            while((group = $bigList.find('li:lt(8)').remove()).length) {
                $('<ul/>').append(group).appendTo(submenu);
            }

        }
        if($("li", this).length > 10){
            $(this).closest(".submenu").addClass("width-3")

        }
    });
}

【问题讨论】:

  • 你可以发布标记吗?
  • 如果您可以在jsFiddle.net 中进行设置,将会非常有帮助
  • 我已经制作了这个 JSFiddle。 jsfiddle.net/xtFPy/1 当您将鼠标悬停在项目上时。您会看到子菜单。当 li 项大于 4 时。子菜单的宽度设置为 320 像素。但问题是。当 li 项大于 4 时,必须将 li 项拆分为两个 ul。而不是 1。
  • 什么是group,似乎while 循环永远不会结束?
  • 当我运行脚本时。当我的浏览器停止时,while 循环正在中断。

标签: javascript jquery split while-loop each


【解决方案1】:

我不完全确定我理解您要做什么,但此代码会将每个子菜单 UL 拆分为更多指定大小的子菜单,同时保持所有项目的原始 DOM 顺序:

function splitSubmenu(maxNumItems) {
    $(".submenu").each(function () {

        // get all child li tags
        var list$ = $(this).children("li");
        var num, nextAfter$, after$ = $(this);

        // as long as the current list it too long, loop
        while (list$.length > maxNumItems) {
            // decide how many to remove this iteration
            num = Math.min(maxNumItems, list$.length - maxNumItems);
            // create new UL tag, append num items to it 
            // and insert it into the DOM
            nextAfter$ = $('<ul class="submenu">')
                .append(list$.slice(maxNumItems, maxNumItems + num))
                .insertAfter(after$);
            // update insertion point for next loop iteration
            after$ = nextAfter$;
            // remove the items we just took out from the current jQuery object
            list$ = list$.filter(function(index) {
                return(index < maxNumItems || index >= 2 * maxNumItems);
            });
        }
    });
}

splitSubmenu(4);

你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/VMjvQ/

我不明白您要对附加类做什么,因此不包括该部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多