jQuery包装相邻元素的组

ben*_*enb 5 css jquery dom

我有一个cms,可让用户在页面上插入内容块。用户可以使用不同类型的内容块,并且可以按任何顺序插入它们。一个示例高级dom结构可能看起来像这样:

<p>Some rich text</p>

<div class="box">...</div>
<div class="box">...</div>
<div class="box">...</div>

<h3>Some  more rich text</h3>
<p>Lorem ipsum</p>

<div class="box">...</div>
<div class="box">...</div>
Run Code Online (Sandbox Code Playgroud)

我想做的就是将所有相邻的“ box” div包裹在一个“ container” div中。因此,在上面的示例中,将插入两个“容器” div,因为有两组box div,结果是:

<p>Some rich text</p>

<div class="container">
    <div class="box">...</div>
    <div class="box">...</div>
    <div class="box">...</div>
</div>

<h3>Some  more rich text</h3>
<p>Lorem ipsum</p>

<div class="container">
    <div class="box">...</div>
    <div class="box">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我认为没有使用CSS选择器的聪明方法,所以有人知道无论如何要使用jQuery吗?

Mos*_*Feu 5

您可以使用

  1. .nextUntil,得到所有的下.box
  2. .andSelf 将当前元素添加到集合中
  3. .wrapAll 将每个集合包装到不同的 .container

$('.box').not('.box+.box').each(function(){
  $(this).nextUntil(':not(.box)').addBack().wrapAll('<div class="container" />');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some rich text</p>

<div class="box">...</div>
<div class="box">...</div>
<div class="box">...</div>

<h3>Some  more rich text</h3>
<p>Lorem ipsum</p>

<div class="box">...</div>
<div class="box">...</div>
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*lly 4

好吧,你可以像我刚刚编写的JSFiddle 示例一样做到这一点。

这基本上循环遍历每个.box将其添加到数组并确定下一个元素是否也具有该类.box

var collection = [];
$('.box').each(function() {
    var nextBox = $(this).next().hasClass('box');
    ...
    collection.push($(this));
})
Run Code Online (Sandbox Code Playgroud)

如果下一个元素没有类,它会创建包含分隔符,将其放在数组中.box第一个分隔符之前的页面上,然后用于将所有分隔符移入其中:.boxcollectionappendTo.box

    if(!nextBox)
    {
        var container = $('<div class="collection"></div>');
        container.insertBefore(collection[0]);
        for(i=0;i<collection.length;i++)
        {
            collection[i].appendTo(container);
        }
        collection = [];
    }
Run Code Online (Sandbox Code Playgroud)