如何使用jQuery将每4个元素移动到另一个容器中

How to move every 4 elements to another container with jQuery?

本文关键字:另一个 移动 元素 何使用 jQuery 将每 4个      更新时间:2023-09-26

所以我有这个标记:

<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如何做到这一点?在这种情况下,我只知道如何包装元素,但不知道如何移动它们:)

如果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>

您可以使用appendTo.newContainer 中移动article

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

相关文章: