2016-01-05 35 views
10

我需要使用jQuery将相同类中具有相同类的相邻元素包装在一个div中。到目前为止,我正在使用.wrapAll函数在div中包装具有相同类的元素。用相同的类包装相邻元素

HTML:

<a class="image"></a> 
<a class="image"></a> 
<a class="image"></a> 
<p>Some text</p> 
<a class="image"></a> 
<a class="image"></a> 

脚本:

$("a.image").wrapAll("<div class='gallery'></div>"); 

输出:

<div class='gallery'> 
    <a class="image"></a> 
    <a class="image"></a> 
    <a class="image"></a> 
    <p>Some text</p> 
    <a class="image"></a> 
    <a class="image"></a> 
</div> 

但是我需要包裹相邻元件与 '图像' 类中单独的div 'galle。' y'级。所以输出需要看起来像这样:

<div class='gallery'> 
    <a class="image"></a> 
    <a class="image"></a> 
    <a class="image"></a> 
</div> 
<p>Some text</p> 
<div class='gallery'> 
    <a class="image"></a> 
    <a class="image"></a> 
</div> 

有没有办法使用jQuery做到这一点?

回答

5
  1. 你得到的不相邻的图像(第一和刚刚p一前一后)通过使用.not功能。
  2. 对于它们中的每一个,您都使用(.nextUntilandSelf)收集相邻图像。
  3. 最后,你将它们包装全部采用.wrapAll

$('.image').not('.image+.image').each(function(){ 
 
    $(this).nextUntil(':not(.image)').andSelf().wrapAll('<div class="gallery" />'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a class="image">1</a> 
 
<a class="image">2</a> 
 
<a class="image">3</a> 
 
<p>Some text</p> 
 
<a class="image">4</a> 
 
<a class="image">5</a>

http://jsbin.com/gonino/edit?html,js

更新这是片断的结果。

enter image description here

+0

优秀的招数.. – KAD

+0

@KAD谢谢;) –