封装兄弟元素[一次两个]与div共享相同的类

时间:2013-11-27 12:10:39

标签: javascript jquery

我有十个兄弟元素,有.post类, 标记类似于:

<div class='book'>
    <div class='post text'>one</div>
    <div class='post photo'>two</div>
    <div class='post quote'>three</div>
    <div class='post video'>four</div>
    <div class='post audio'>five</div>
    <div class='post link'>six</div>
    <div class='post text'>seven</div>
    <div class='post video'>eight</div>
    <div class='post quote'>nine</div>
    <div class='post link'>ten</div>
</div>

我希望.post div一次封装两个div(比如类.page),所以标记看起来像:

<div class='book'>
    <div class='page'>
        <div class='post text'>one</div>
        <div class='post photo'>two</div>
    </div>
    <div class='page'>
        <div class='post quote'>three</div>
        <div class='post video'>four</div>  
    </div>
    <div class='page'>  
        <div class='post audio'>five</div>
        <div class='post link'>six</div>
    </div>
    <div class='page'>    
        <div class='post text'>seven</div>
        <div class='post video'>eight</div>
    </div>
    <div class='page'>    
        <div class='post quote'>nine</div>
        <div class='post link'>ten</div>
    </div>
</div>

这是针对tumblr布局的。我希望布局看起来像一本书,你可以在其中翻阅像la:http://jsfiddle.net/9fdk047t/这样的帖子。

我遇到了z-index&amp;的问题。在transition s没有包装div时尝试.post。{/ p>

我用十个作为例子。页面上可能有1-10个.post,因此如果页面上有奇数个.post s,则最后一个封装div应该只承载一个.post

jsfiddle:http://jsfiddle.net/jklm313/Upb3S/1/

谢谢你的帮助!

3 个答案:

答案 0 :(得分:6)

可以使用.wrapAll()方法完成:

$('.post').each(function (i) {
    if (!(i % 2)) $(this).next('.post').addBack().wrapAll('<div class="page"/>');
});

DEMO

答案 1 :(得分:1)

var posts = $('.post');
for(var i=0; i < posts.size(); i+=2) {
    var group = $(posts.get(i)).add($(posts.get(i+1)));
    group.addClass('group');
    $('.group').wrapAll('<div class="page" />');
    group.removeClass('group');
}

答案 2 :(得分:1)

沃尔夫的答案绝对是紧凑的,我从中学到了很多东西  这是我试过的,冗长的......:)

$(document).ready(function () {
    var book = $('.book');
    var postgroups = [];
    var postitems = [];
    var addItems = function () {
        var grpDiv = $('<div class ="page"/>');
        $(grpDiv).append(postitems);
        postitems = [];
        postgroups.push(grpDiv);
    }
    $('.post').each(function (index, item) {
        postitems.push(item);
        if ((index + 1) % 2 == 0) {
            addItems();
        }
    });
    if (postitems.length > 0) {
        addItems();
    }
    if (postgroups.length > 0) {
        $(book).empty();
        $(book).append(postgroups);
    }
});