在div中每隔3个div [英] Wrap every 3 divs in a div

查看:115
本文介绍了在div中每隔3个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用 nth-child 选择器使用 .wrapAll 包装3个div吗?

Is it possible to use nth-child selectors to wrap 3 divs using .wrapAll? I can't seem to work out the correct equation.

所以...

<div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</div>

成为...

<div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
</div>


推荐答案

您可以使用 .slice() ,例如:

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>");
}

你可以在这里尝试一个演示,我们在这里做的是获取你想要包装和循环遍历他们的元素,做一个 .wrapAll() 批次3,然后移动到下3个等。将一次包装3,然而许多都留在结束,例如3,3,3,2如果是这样。

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.

这篇关于在div中每隔3个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆