使用jQuery将ul拆分为更多ul

时间:2012-04-27 20:47:33

标签: javascript jquery split while-loop each

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

但脚本无效。我在这里做错了什么。 该脚本用于导航中的子菜单。当导航li项目超过4项时,必须将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")

        }
    });
}

1 个答案:

答案 0 :(得分:0)

我不完全确定我理解你要做的是什么,但是这段代码会将每个子菜单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/

我不明白你试图用其他类做什么,所以不包括部分。

相关问题