我正在尝试选择div并使用第n个子项将它们包装在bootstrap列中。
我有:
<div class="owl-news">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
</div>
目前我已经尝试过(因为div有类'news-v2'):
var divs = $(".owl-news > .news-v2");
for (var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='col-md-2'></div>");
}
给出以下输出:
<div class="owl-news">
<div class="col-md-2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
</div>
<div class="col-md-2">
<div class="item news-v2">
<div class="item news-v2">
<div class="item news-v2">
</div>
<div class="col-md-2">
<div class="item news-v2">
<div class="item news-v2">
</div>
</div>
但是这只包含了col-md-2中的每3个div,我需要专门选择第一个div,接下来的2个,接下来的2个和最后一个3.生成我想要的内容:
<div class="owl-news">
<div class="col-md-4">
<div class="item news-v2"></div>
</div>
<div class="col-md-3">
<div class="item news-v2"></div>
<div class="item news-v2"></div>
</div>
<div class="col-md-3">
<div class="item news-v2"></div>
<div class="item news-v2"></div>
</div>
<div class="col-md-2">
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
</div>
</div>
答案 0 :(得分:1)
嗯,不幸的是,由于您想要的格式并不真正遵循任何模式,因此您可以进行任意选择。
请参阅下面的代码。
var divs = $(".owl-news > .news-v2");
let array = [
{ length: 1, num: 4 },
{ length: 2, num: 3 },
{ length: 2, num: 3 },
{ length: 3, num: 2 }
];
let i = 0;
for (let item of array) {
divs.slice(i, i+item.length).wrapAll(`<div class='col-md-${item.num}'></div>`);
i += item.length;
}
console.log($(".owl-news").html());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="owl-news">
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
<div class="item news-v2"></div>
</div>
&#13;
您的代码无法正常工作的原因是因为您总是添加3 divs.slice(i, i+3)
并始终使用&#34; md-2&#34; .wrapAll("<div class='col-md-2'></div>");