1

我的代码围绕每 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/

4

1 回答 1

0

如果您使用 Ids 来识别内容 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>

在小提琴中检查它

于 2014-02-18T14:56:27.187 回答