복붙노트

[JQUERY] 사업부에 매 3 명 div가 랩

JQUERY

사업부에 매 3 명 div가 랩

해결법


  1. 1.이 같은 .slice ()와 함께 할 수 있습니다 :

    이 같은 .slice ()와 함께 할 수 있습니다 :

    var divs = $("div > div");
    for(var i = 0; i < divs.length; i+=3) {
      divs.slice(i, i+3).wrapAll("<div class='new'></div>");
    }
    

    당신은 우리가 여기에서하고있는 모든 당신이 포장 할 요소를 얻고이를 통해 반복, 그 다음 3으로 이동 3의 배치에 .wrapAll을 ()하고있다, 여기에서 데모를 시도 할 수 있습니다, 등이 3 바꿈됩니다 한 번에하고 그러나 많은 사람들이 마지막 예에서 남아 있습니다 3, 3, 3, 2 그런 경우.


  2. 2.내가 할이 매우 쉽게 일반적인 청크 기능을 작성했습니다 :

    내가 할이 매우 쉽게 일반적인 청크 기능을 작성했습니다 :

    $.fn.chunk = function(size) {
        var arr = [];
        for (var i = 0; i < this.length; i += size) {
            arr.push(this.slice(i, i + size));
        }
        return this.pushStack(arr, "chunk", size);
    }
    
    $("div > div").chunk(3).wrap('<div class="new"></div>');
    

    $ .fn.chunk = 함수 (크기) { VAR의 도착 = []; {위해 (I + = 크기; I <식에서 나타내지 VAR 난 = 0) arr.push (this.slice (I, I + 크기)); } 반환 this.pushStack (편곡, "덩어리", 크기); } $ ( "div> DIV") 덩어리 (3) .wrap ( '

    .'); DIV> DIV { 넓이 : 50 픽셀; 높이 : 50 픽셀; 배경 : 파란색; 마진 : 2 픽셀; 왼쪽으로 뜨다; } div.new { 배경 : 빨간색; 높이 : 자동; 폭 : 자동; 오버 플로우 : 자동; } <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">


  3. 3.

    $(function() {
        $.fn.EveryWhat = function(arg1) {
            var arr = [];
            if($.isNumeric(arg1)) {
                $.each(this, function(idx, item) {
                    var newNum = idx + 1;
                    if(newNum%arg1 == 0)
                    arr.push(item);
                });
            }
            return this.pushStack(arr, "EveryWhat", "");
        }
    });
    

    요소에 전화 EveryWhat () 및 수집하고자하는 모든 요소의 번호에 넣어.

    $("div").EveryWhat(2).wrapInner('<div class="new" />');
    

    wrapinner의 따옴표가 올바른 형식이 있어야

    클래스와 닫는 태그. 여기처럼 보이지만이 자기 닫는 사업부의 링크가 무엇인지 보여주는에서 유래 방지 나.

    그것은 당신이 지정한 다른 모든 수를 바꿈됩니다. 나는 JQuery와 1.8.2를 사용하고 있습니다. 그래서 사용을 선택 호출 EveryWhat (3) 모든 시간들을 기억한다. 물론 페이지 하단에 퍼팅 또는 그것을 포장의

    $(document).ready(function() {  
        //place above code here
    });
    

    동일한 결과를 다음 모든 n 번째와 .wrapInner ( "

    ')를 사용할 수 있습니다.


  4. 4.여기에 닉의 위의 더 사용할 수있는 버전입니다 :

    여기에 닉의 위의 더 사용할 수있는 버전입니다 :

    window.WrapMatch = function(sel, count, className){
      for(var i = 0; i < sel.length; i+=count) {
        sel.slice(i, i+count).wrapAll('<div class="'+className+'" />');
      }
    }
    

    이 작업을 같이 사용합니다 :

    var ele = $('#menu > ul > li'); 
    window.WrapMatch(ele, 5, 'new-class-name');
    

    윈도우는 물론, 핸들러 네임 스페이스로 교체해야합니다.

    업데이트 : 약간 더 나은 버전이 레버리지 jQuery를

    (function($){
      $.fn.wrapMatch = function(count, className) {
        var length = this.length;
        for(var i = 0; i < length ; i+=count) {
          this.slice(i, i+count).wrapAll('<div '+((typeof className == 'string')?'class="'+className+'"':'')+'/>');
        }
        return this;
      }; 
    })(jQuery);
    

    사용 같은 :

    $('.list-parent li').wrapMatch(5,'newclass');
    

    래퍼 이름에 대한 두 번째 매개 변수는 선택 사항입니다.


  5. 5.

    $(function() {
        $.fn.WrapThis = function(arg1, arg2) { /*=Takes 2 arguments, arg1 is how many elements to wrap together, arg2 is the element to wrap*/
    
            var wrapClass = "column"; //=Set class name for wrapping element
    
            var itemLength = $(this).find(arg2).length; //=Get the total length of elements
            var remainder = itemLength%arg1; //=Calculate the remainder for the last array
            var lastArray = itemLength - remainder; //=Calculate where the last array should begin
    
            var arr = [];
    
            if($.isNumeric(arg1))
            {
                $(this).find(arg2).each(function(idx, item) {
                    var newNum = idx + 1;
    
                    if(newNum%arg1 !== 0 && newNum <= lastArray){
                        arr.push(item);
                    }
                    else if(newNum%arg1 == 0 && newNum <= lastArray) {
                        arr.push(item);
                        var column = $(this).pushStack(arr);
                        column.wrapAll('<div class="' + wrapClass + '"/>'); //=If the array reaches arg1 setting then wrap the array in a column
                        arr = [];
                    }
                    else if(newNum > lastArray && newNum !== itemLength){ //=If newNum is greater than the lastArray setting then start new array of elements
                        arr.push(item);
                    }
                    else { //=If newNum is greater than the length of all the elements then wrap the remainder of elements in a column
                        arr.push(item);
                        var column = $(this).pushStack(arr);
                        column.wrapAll('<div class="' + wrapClass + '"/>');
                        arr = []
                    }
                });
            }
        }
    });
    

    나는 카일의 플러그인 생각을했다 자동 포장 및 두 개의 인수를 취할를 확장. 나에게로 시작하는 것은 작동하지 않았다,하지만 난 그것을 코드에 몇 가지 편집 및 추가로 실행되었다.

    함수를 호출하기 위해 당신이 포장 할 다음과 같이 다음 인수를 설정 어떤 부모 요소를 사용합니다.

    $('#container').WrapThis(5, 'li');
    

    첫 번째 인수는 함께 포장 할 두 번째 인수는 포장하고 싶은 요소 유형 얼마나 많은 요소이다.

    당신은 변수 wrapClass 아래의 주요 기능에 포장 요소의 클래스를 변경할 수 있습니다.


  6. 6.나는이 하나의 중복이었다 다른 질문이 답을 준비 하였다. 그래서 어쩌면 내 변형은 어떤 사람을 위해 유용 할 것입니다 :

    나는이 하나의 중복이었다 다른 질문이 답을 준비 하였다. 그래서 어쩌면 내 변형은 어떤 사람을 위해 유용 할 것입니다 :

    나는의 해결책이 세 가지 요소를 래핑하는 생각 :

    var $lines = $('.w-col'), // All Dom elelements with class .w-col
         holder = []; //Collect DOM elelements
    
    $lines.each(function (i, item) {
      holder.push(item);
    
      if (holder.length === 3) {
        $(holder).wrapAll('<div class="w-row" />');
        holder.length  = 0;
      }
    });
    
    $(holder).wrapAll('<div class="w-row" />'); //Wrap last elements with div(class=w-row)
    

    나는 몇 가지 개선 jsbin에서 동일한 코드를 썼다 http://jsbin.com/necozu/17/ 또는 http://jsbin.com/necozu/16/

  7. from https://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div by cc-by-sa and MIT license