jquery wrapping groups of adjacent elements

前端 未结 3 1540
我寻月下人不归
我寻月下人不归 2020-12-19 09:36

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 e

3条回答
  •  旧时难觅i
    2020-12-19 10:00

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

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

    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 = $('
    '); container.insertBefore(collection[0]); for(i=0;i

提交回复
热议问题