如何包装项目周围的div?

时间:2014-02-18 14:26:50

标签: javascript jquery wrapall

我的代码在每5个子div中包含一个div。 但是包装应该只在div“partnerwrap”中进行,有人可以帮助我吗?

var divs = $(".partnerwrap > .partner_item");
for (var i = 0; i < divs.length; i += 5) {
  divs.slice(i, i + 5).wrapAll("<div class='group'></div>");
}
.partner_item {
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content1">
  <div class="partnerwrap">
    <div class="partner_item even">1</div>
    <div class="partner_item odd">2</div>
    <div class="partner_item even">3</div>
    <div class="partner_item odd">4</div>
    <div class="partner_item even">5</div>
    <div class="partner_item odd">6</div>
    <div class="partner_item even">7</div>
    <div class="partner_item odd">8</div>
  </div>
</div>
<div class="content2">
  <div class="partnerwrap">
    <div class="partner_item even">9</div>
    <div class="partner_item odd">10</div>
  </div>
</div>

的jsfiddle: http://jsfiddle.net/nvnLa/1/embedded/result/

1 个答案:

答案 0 :(得分:0)

如果您使用ID来识别内容div,并使用class对它们进行分组,您可以执行以下操作:

$(".content").each(function() {
  var divs = $(".partnerwrap > .partner_item", this);
  for (var i = 0; i < divs.length; i += 5) {
    divs.slice(i, i + 5).wrapAll("<div class='group'></div>");
  }
});
.partner_item {
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content1">
  <div class="partnerwrap">
    <div class="partner_item even">1</div>
    <div class="partner_item odd">2</div>
    <div class="partner_item even">3</div>
    <div class="partner_item odd">4</div>
    <div class="partner_item even">5</div>
    <div class="partner_item odd">6</div>
    <div class="partner_item even">7</div>
    <div class="partner_item odd">8</div>
  </div>
</div>
<div class="content2">
  <div class="partnerwrap">
    <div class="partner_item even">9</div>
    <div class="partner_item odd">10</div>
  </div>
</div>

fiddle

中查看