jQuery如何将div包装在多个相同的类元素中 [英] jQuery How to wrap div around multiple of the same class elements

查看:90
本文介绍了jQuery如何将div包装在多个相同的类元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将多个相同的类div包装到div中,并跳过不具有相同类的div。 .wrap不会合并它们,并且.wrapAll会在下面引发非分类的div。我一直在试图创建一个替代解决方案,但没有用。



原始

 < div class =entry>内容< / div> 
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< div>跳过换行< / div>
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< div class =entry>内容< / div>

续...

通缉结果

 < div> 
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< / div>
< div>跳过换行< / div>
< div>
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< div class =entry>内容< / div>
< / div>


解决方案

c>< div> 元素使用作为循环。在下面的代码中,只需在这里改变初始选择器来获取所有的兄弟div,例如 #content> div.entry 或无论它们在哪里:

  var divs = $(div.entry) ; $(&); 
for(var i = 0; i

i + = divs.eq(i).nextUntil(':not(.entry)')。andSelf()。wrapAll '< div />').length;
}

你可以在这里试试看。我们只是循环使用 .entry < div> 元素,使用 .nextUntil() 获取所有 .entry 元素,直到使用 .entry rel =noreferrer> :not()选择器。然后,我们将采用下一个元素,加上我们开始的元素( .andSelf() )并执行 .wrapAll() 。在它们被包装后,我们正在跳过循环中的许多元素。


I'm trying to wrap multiple same class divs into a div and to skip divs not with the same class. .wrap doesn't combine them, and .wrapAll throws the non-classed divs underneath. I've been tinkering around with attempts to create an alternate solution but with no avail.

Original

<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div>Skip in wrap</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>

continued...

Wanted Result

<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>
<div>Skip in wrap</div>
<div>
<div class="entry">Content</div>
<div class="entry">Content</div>
<div class="entry">Content</div>
</div>

解决方案

You can loop pretty quickly through your <div> elements using a for loop. In the below code, just change the initial selector here to grab all those siblings divs, e.g. #content > div.entry or wherever they are:

var divs = $("div.entry");
for(var i=0; i<divs.length;) {
  i += divs.eq(i).nextUntil(':not(.entry)').andSelf().wrapAll('<div />').length;
}​

You can give it a try here. We're just looping through, the .entry <div> elements using .nextUntil() to get all the .entry elements until there is a non-.entry one using the :not() selector. Then we're taking those next elements, plus the one we started with (.andSelf()) and doing a .wrapAll() on that group. After they're wrapped, we're skipping ahead either that many elements in the loop.

这篇关于jQuery如何将div包装在多个相同的类元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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