문제

긴 UL 목록이 있습니다. 각각 약 20 개의 항목이 포함 된 작은 목록에서 헤어져야합니다.

나는 내가 같은 것을 사용할 수 있다고 생각했다

$(function() {
    $("ul li:nth-child(20n)").after("</ul><ul>");
});

그러나 그것은 사실이 아닙니다. 최소한의 CPU를 사용하는 방식으로 jQuery를 사용하는 방법을 아는 사람이 있습니까?

도움이 되었습니까?

해결책

제거 된 상태에서 문서 조각을 만들 것입니다 li그런 다음 원하는 위치에 다시 나타냅니다. 이 경우, 나는 그들을 몸에 다시 나타냈다.

$(function(){
  var $bigList = $('#bigList'), group;
  while((group = $bigList.find('li:lt(20)').remove()).length){
    $('<ul/>').append(group).appendTo('body');
  }
});

라이브 데모는 다음과 같습니다. http://jsbin.com/ejigu/33

다른 팁

불행히도 그렇게 간단한 것은 없습니다. 대안으로 이것을 시도하십시오.

$(function() {
  $("ul").each(function() {
    var list = $(this);
    var size = 3;
    var current_size = 0;
    list.children().each(function() {
    console.log(current_size + ": " + $(this).text());
      if (++current_size > size) {
        var new_list = $("<ul></ul>").insertAfter(list);
        list = new_list;
        current_size = 1;
      }
      list.append(this);
    });
  });
});

의심 할 여지없이 이것을 청크 크기를 인수로 취하는 함수로 바꿀 수는 있지만 독자를위한 운동으로 남겨 둡니다.

다음은 작업 예입니다. Mod 5를 Mod 20으로 변경하십시오.

<html>
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<script type="text/javascript">

function onLoad(){
   var itemindex = 0;
   var Jlistobj = null;
   $('#list li').each(function()
   {
      if (itemindex % 5 == 0)
      {
         Jlistobj = $("<ul></ul>");
      }
      Jlistobj.append($(this));
      $('#out_div').append(Jlistobj);
      itemindex++;
   });
}

</script>
<body onLoad="onLoad()">

<ul id="list">
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
<li>item9</li>
<li>item10</li>
<li>item11</li>
<li>item12</li>
<li>item13</li>
<li>item14</li>
<li>item15</li>
<li>item16</li>
<li>item17</li>
<li>item18</li>
<li>item19</li>
<li>item20</li>
</ul>

<div id="out_div"></div>

</body>

</html>

기능:

$.fn.splitUp=function(splitBy,wrapper) {
    $all= $(this).find('>*');
    var fragment=Math.ceil($all.length/splitBy);  
    for(i=0; i< fragment; i++) 
        $all.slice(splitBy*i,splitBy*(i+1)).wrapAll(wrapper);
    return $(this);
}

용법:

$('ul#slides').splitUp(4,'&lt;li class=splitUp&gt;&lt;ul&gt;')

또는:

$('div#slides').splitUp(3,'&lt;div/&gt;')

이것은 메뉴를 대략 동일한 길이 함수 splitmenu (menu_id, pieces)의 조각으로 나눕니다.

        var $menu = $(menu_id), group;
        var splitItem = 0, totItemLen = 0, cumlen = 0;

        $($menu).find('li').each(function(){ totItemLen = totItemLen + $(this).width(); });

        $($menu).find('li').each(function(i){
            cumlen = cumlen + $(this).width();
            if ( totItemLen/pieces < cumlen && splitItem == 0) splitItem = i;  
        });

        while((group = $($menu).find('li:lt(' + splitItem + ')').remove()).length){
                $('<ul/>').attr('class',$($menu).attr('class')).append(group).appendTo($($menu).parent());
          }

        $($menu).remove();  
    }  
    splitMenu('#menu-footermenu', 2);

jQuery 플러그인으로서의 다른 버전 :

jQuery.fn.splitList = function(num) {
  var sublist;
  while((sublist = this.find('li:gt('+(num-1)+')').remove()).length){
    this.after($('<ul/>').append(sublist));
  }
};

다음은 또 다른 옵션입니다. 위의 어느 것도 프로파일하지 않았으므로 물론 가장 빠른 것과 함께 가십시오. 문제의 UL에 #List의 ID가 있다고 가정합니다.

     var listItemsPerList = 10;
     var listItems = $("ul > li").length;

     for (var i = 0; i < Math.round(listItems / listItemsPerList); i++) {
         var startingItem = i * listItemsPerList;
         var endingItem = (i + 1) * listItemsPerList;
         if (endingItem > listItems) { endingItem = listItems };
         $("ul > li").slice(startingItem, endingItem).wrapAll("<ul></ul>");
     }

     $("ul#list").replaceWith($("ul#list").children());

다음과 같은 것을 시도 할 수 있습니다.

$("ul").each(function(k,v)){
    split_list(v);
}

function split_list(list){
    var li_num = $(list).find("li").length;
    if(li_num > 20){
        var new_list = $("<ul></ul>");
        $(list).after(new_list);
        new_list.append($(list).find("li:gt(20)"));
        if(new_list.find("li").length > 20){
            split_list(new_list);
        }
    }
}

LE : 나는 새로운 목록이 얼마나 많은 새 목록을 찾아서, 그 목록을 만들고, ~ 20 li의 블록을 새 생성 된 목록으로 이동시켜 한 번만 이동할 것입니다.

다음은 jQuery 프로토 타입 ($ .fn) 객체의 확장으로 jQuery () 함수에 연결될 수있는 새로운 방법을 제공합니다.

분할 목록 사이에 요소를 추가 해야하는 기능이 필요했습니다. 이는 선택적 매개 변수로 추가되었습니다.

예를 들어 볼 수 있습니다 http://jsfiddle.net/roeburg/5f2hw/

함수의 사용은 그렇습니다.

 $("ul").customSplitList(5);

함수는 다음과 같이 정의됩니다.

// Function definition
(function ($) {
    // Function is defined here ...
    $.fn.customSplitList = function (indexToSplit, elementToAddInBetween) {
        // Holds a reference to the element(list)
        var that = this;
        var subList, newList, listLength;

        // Only continue if the element is a derivitive of a list
        if ($(that) && ($(that).is("ul") || $(that).is("ol"))) {

            // Additionally check if the length & the split index is valid
            listLength = $(that).children().length;

            if ($.isNumeric(indexToSplit) && indexToSplit > 0 && indexToSplit < listLength) {
                // Based on list type, create a new empty list
                newList = $($(that).clone(true)).empty();

                while ((subList = this.find('li:gt(' + (indexToSplit - 1) + ')').remove()).length) {
                    newList.append(subList);
                }

                if (elementToAddInBetween && $(elementToAddInBetween)) {
                    that.after(newList);
                    newList.before(elementToAddInBetween);
                } else {
                    that.after(newList);
                }
            }
        }
    };

})(jQuery);

도움이 되었기를 바랍니다.

이 같은:

var lis = $("ul > li");
for(var i = 0; i < lis.length; i+=20) {
  lis.slice(i, i+20).wrapAll("<ul></li>");
}
$("ul > ul").unwrap();

작동하는 데모

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top