2

我想选择每 4 个 divclass "contents"并将其包装在另一个使用动态创建的新 div 中Jquery。我的HTML如下;

<body>
<div id="postings">
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
</div>
</body>

我想

<body>
<div id="postings">
<div id="newDivforWraping1">
    <div class="contents"></div>
     <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
</div>
<div id="newDivforWraping2">
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
</div>
<div id="newDivforWraping3">
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
    <div class="contents"></div>
</div>
</div>
</body>

我当前的 JScript 代码如下;

(function() {
    "use strict";
    $(document).ready(function() {
        insertdiv("newDivforWraping1",4);
        insertdiv("newDivforWraping2",8);
        insertdiv("newDivforWraping3",12);
        });

        //create div for every grouping them into three
        function insertdiv(divname,n) {
            $("<div/>", {class: "test",id:divname}).appendTo("#postings");
            var allcontentspost = $(".contents").each();
            for (var i=n-4;i<n;i++) {
                allcontentspost[i].appendTo("#"+divname);
            };
        }
})();
4

3 回答 3

7

您可以使用slice获取数字,然后wrapAll

var divs = $(".contents");
for(var i = 0; i < divs.length; i+=4) {
   j = i + 1; 
  divs.slice(i, i+4).wrapAll("<div id='newDivforWraping"+j+"' class='new'></div>");
}

看一下这个

http://jsfiddle.net/RQNrt/

我希望这可以帮助

于 2013-07-30T04:45:21.617 回答
2

DEMO

var sel;
var count = 1;
while ((sel = $('#postings > div.contents')).length > 0) {
    sel.slice(0, 4).wrapAll('<div class= "test" id="newDivforWraping' + count+++'"></div>');
}
于 2013-07-30T04:45:55.217 回答
0

希望这会有所帮助:代码

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

wrappings = [];
elems = 0; // from 1 to 4
count = 0;
$.each($('div.contents'), function (index, elem) {
    if (elems == 4) {
        elems = 0;
        count++;
    }
    console.log('count:' + count);
    if (! wrappings[count]) {
        wrappings[count] = []
    }
    wrappings[count].push($(elem).outerHTML());

    elems++;
});
console.log(wrappings);
$.each(wrappings, function (index, w) {
    wrappings[index] = w.join('');
});

bigHTML = '';
$.each(wrappings, function (index, w) {
    bigHTML += '<div id="newWrap_' + index + '">';
    bigHTML += w;
    bigHTML += '</div>'
});
$('div#postings').html(bigHTML);
于 2013-07-30T04:57:12.417 回答