jquery包装组的相邻元素 [英] jquery wrapping groups of adjacent elements

查看:109
本文介绍了jquery包装组的相邻元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a cms that lets users insert blocks of content on a page. There are different types of content block available to the user and they can be inserted in any order. An example high-level dom structure might look something like this:

<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>

我想做的是将任何相邻的box因此,在上面的示例中,将插入两个containerdiv,因为有两组box div,导致:

What I want to do is wrap any adjacent 'box' divs in a wrapping 'container' div. So in the example above there would be two 'container' divs inserted as there are two groups of box divs, resulting in:

<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>

我不认为有一个聪明的方法来做它与css选择器,

I don't think there is a clever way to do it with css selectors, so does anyone know of anyway to do this with jQuery?

。/ 7NCDf /rel =nofollow> JSFiddle示例我刚刚开始。

Well you could do it like this JSFiddle example I've just whipped up.

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

This basically loops through each .box adding it to an array and determining whether the next element also has the .box class:

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

下一个元素不会 .box 类,它会创建包含分隔符,将其放在第一个集合数组中找到<。 c。> .box ,然后使用 appendTo .box 分隔符:

If it the next element doesn't have a .box class, it creates the containing divider, puts it on the page before the first .box within the collection array is located, then uses appendTo to move all the .box dividers into it:

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

这篇关于jquery包装组的相邻元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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