将每 3 个 div 包装在一个 div 中 [英] Wrap every 3 divs in a div
问题描述
是否可以使用 nth-child
选择器使用 .wrapAll
包装 3 个 div?我似乎无法计算出正确的方程式.
所以...
<div></div><div></div><div></div><div></div><div></div><div></div>
变成……
<div class="new"><div></div><div></div><div></div><div class="new"><div></div><div></div><div></div>
您可以使用 来完成.slice()
,像这样:
var divs = $("div > div");for(var i = 0; i < divs.length; i+=3) {divs.slice(i, i+3).wrapAll("<div class='new'></div>");}
您可以在此处试用演示,我们在这里所做的只是获取您需要的元素想要对它们进行包装和循环,在 .wrapAll()
中执行3 个批次然后移动到下一个 3 等.它一次会包裹 3 个,但最后还剩下很多,例如3, 3, 3, 2 如果是这样的话.
Is it possible to use nth-child
selectors to wrap 3 divs using .wrapAll
? I can't seem to work out the correct equation.
so...
<div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
becomes...
<div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
</div>
You can do it with .slice()
, like this:
var divs = $("div > div");
for(var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='new'></div>");
}
You can try out a demo here, all we're doing here is getting the elements you want to wrap and looping through them, doing a .wrapAll()
in batches of 3 then moving to the next 3, etc. It will wrap 3 at a time and however many are left at the end, e.g. 3, 3, 3, 2 if that's the case.
这篇关于将每 3 个 div 包装在一个 div 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!