1

I have made a script with jQuery. The script split a list of li's, to more ul's. When the list is moer than 10 li items the list must be split in more ul's. I have made the script in this post.

But the script is not working. What I did wrong here. The script is for a submenu in the navigation. When the navigation li items are more than 4 than the ul of li items must be splitted in two ul's. How can I fix this script. Thanks!

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")

        }
    });
}
4

1 に答える 1

0

あなたが何をしようとしているのか完全にはわかりませんが、このコードは、すべての項目を元の DOM 順序に保ちながら、各サブメニュー UL を指定されたサイズのサブメニューに分割します。

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/で動作することがわかります。

追加のクラスで何をしようとしているのかわからなかったので、その部分は含まれていません。

于 2012-04-27T21:23:23.243 に答える