3 개 div를 div로 래핑


85

nth-child선택기를 사용하여 3 개 div를 래핑 할 수 .wrapAll있습니까? 나는 정확한 방정식을 풀 수없는 것 같다.

그래서...

<div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</div>

된다 ...

<div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
</div>

2
gist.github.com/3181731 정확히 그렇게하기위한 멋진 jQuery 플러그인. 유용하게 사용되기를 바랍니다.
iMoses 2012-07-26

답변:


179

다음과 .slice()같이으로 할 수 있습니다 .

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

여기 에서 데모를 시도해 볼 수 있습니다. 여기서 수행하는 작업은 래핑하고 반복하려는 요소를 가져 와서 .wrapAll()3 개씩 배치 한 다음 다음 3 개로 이동하는 등의 작업입니다. 한 번에 3 개씩 래핑하고 그러나 마지막에 3, 3, 3, 2가 남아 있습니다.


나는 이것을 함수로 만들고 래핑 된 div의 수를 인수로 만들 것입니다. applyDivGrouping (divs, divsPerGroup);
Stefan Kendall

와! 신속한 답변에 감사드립니다. 몇 가지 ... 그래서, 설명을 위해-nth-child를 사용하면 불가능합니까? & .. 완전한 jQuery 초보자로서이 기능을 사용하려면 어떻게해야합니까? 내가 jQuery를 (함수 ($)에 포장 마 ... 많은 감사?
csbourne

@csbourne-Nope :nth-child()는 이것에 대해 잘 빌려주지 않습니다. 이것을 부르는 것에 $(function() { });관해서는 document.ready, 그것을 실행하고 싶다면 그냥 감싸고 , 그렇지 않으면 실행하고 싶을 때 호출하십시오 :)
Nick Craver

환상적인 도움과 안내에 대해 Nick에게 감사드립니다-완벽하게 작동합니다.
csbourne 2010

3
@Fahad, NickCraver 논리에 따라, 당신이 할 수있다 코드를 간단하게 편집 작은 조각 var divs = $("div > .classname");또는 var divs = $("div .classname");감사

23

이 작업을 매우 쉽게 만드는 일반적인 청크 함수를 작성했습니다.

$.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>');


8

플러그인

$(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의 따옴표는 <div class="new" />클래스와 닫는 태그 로 적절하게 형식 을 지정해야합니다 . Stackoverflow는 그것이 어떻게 생겼는지 보여주지 못하도록 막지 만 여기에 자체 폐쇄 div의 링크가 있습니다.

어떻게 생겼는지

지정한 다른 모든 번호를 래핑합니다. jquery 1.8.2를 사용하고 있습니다. 따라서 EveryWhat(3)항상 선택기 호출 과 번호를 사용하십시오 . 물론 페이지 하단에 두거나

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

n 번째마다 사용할 수 .wrapInner('<div class="new" />')있으며 동일한 결과를 얻을 수 있습니다.


1
이미이 작업을 수행 할 수 있으며 $('div > div:nth-child(3n)')실제로 세 요소의 두 그룹이 생성되지는 않습니다.
Ja͢ck

7

위의 Nick의 더 유용한 버전은 다음과 같습니다.

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');

물론 창을 Handlers 네임 스페이스로 바꿔야합니다.

업데이트 됨 : 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');

랩퍼 이름의 두 번째 매개 변수는 선택 사항입니다.


1
$(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 = []
                }
            });
        }
    }
});

나는 Kyle의 플러그인 아이디어를 가져와 자동으로 래핑하고 두 가지 인수를 취하도록 확장했습니다. 처음에는 작동하지 않았지만 코드를 몇 가지 편집하고 추가하여 실행했습니다.

함수를 호출하려면 래핑하려는 항목의 부모 요소를 사용하고 다음과 같이 인수를 설정하십시오.

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

첫 번째 인수는 함께 래핑하려는 요소의 수이고 두 번째 인수는 래핑하려는 요소 유형입니다.

변수 아래의 main 함수에서 래핑 요소의 클래스를 변경할 수 있습니다 wrapClass.


0

이 질문과 중복되는 다른 질문에 대해이 답변을 준비했습니다. 따라서 내 변형이 일부에 유용 할 수 있습니다.

세 가지 요소를 모두 감싸는 해결책은 다음과 같습니다.

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)

http://jsbin.com/necozu/17/ 또는 http://jsbin.com/necozu/16/ 일부 개선 사항으로 jsbin에서 동일한 코드를 작성했습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.