2012-04-27 47 views
1

我用jQuery製作了一個腳本。腳本將李的列表分割爲更多的ul。當列表比10個項目更多時,該列表必須被分成更多的ul。 我已經在這篇文章中做了腳本。將ul分解爲更多ul的jQuery

但該腳本無法正常工作。我在這裏做錯了什麼。 該腳本用於導航中的子菜單。當導航鋰項目超過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

你可以發佈標記嗎? – mattytommo 2012-04-27 20:52:15

+2

如果你可以在http://jsFiddle.net中設置這個,我真的會有幫助 – 2012-04-27 20:55:59

+0

我已經制作了這個JSFiddle。 http://jsfiddle.net/xtFPy/1/ 當您將鼠標懸停在項目上時。你看到子菜單。當li項目大於4.時,子菜單的寬度設置爲320像素。 但問題是。當li項目超過4個時。li項目必須分成兩個ul。而不是1. – 2012-04-27 20:58:51

回答

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/

我不明白你正在試圖做什麼額外的類,以便不包括部分。