2015-07-02 61 views
0

所以我有這個標記:如何使用jQuery將每4個元素移動到另一個容器?

<section class="oldContainer"> 
    <article></article> 
    <article></article> 
    <article></article> 
    <article></article> 
    <article></article> 
    <article></article> 
</section> 
<section class="newContainer"></section> 
<section class="newContainer"></section> 

而且我想所有<article>'soldContainer移動到newContainer,但這樣的newContainer可以有不超過4 <article>'s每個。這怎麼能用jQuery來完成?我只知道如何包裝元素在這種情況下,而不是將它們移動:)

+1

從'oldcontainer'獲取所有元素,迭代它們,爲'newContainer'創建html,'從oldcontainer'移除'',並在'newContainer'中插入 –

回答

6

如果newcontainer元素已經存在,那麼,你可以只移動它們

var $as = $('.oldContainer article'); 
 
$('.newContainer').each(function(i) { 
 
    $(this).append($as.slice(i * 4, (i + 1) * 4)) 
 
});
.oldContainer { 
 
    min-height: 5px; 
 
    border: 1px solid red; 
 
    margin-bottom: 5px; 
 
} 
 
.newContainer { 
 
    min-height: 5px; 
 
    border: 1px solid green; 
 
    margin-bottom: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<section class="oldContainer"> 
 
    <article>1</article> 
 
    <article>2</article> 
 
    <article>3</article> 
 
    <article>4</article> 
 
    <article>5</article> 
 
    <article>6</article> 
 
</section> 
 
<section class="newContainer"></section> 
 
<section class="newContainer"></section>

2

你可以使用appendTo移動article.newContainer

var i = 0; // To get the .newContainer by index 

// Run until there is no article left in .oldContainer 
while ($('.oldContainer article').length) { 
    $('.oldContainer article:lt(4)').appendTo($('.newContainer').eq(i++)); 

    // Get first four `article` and move it to the .newContainer element 
} 

DEMO

相關問題