简体   繁体   English

如何包装彼此相邻且具有相同类的所有元素?

[英]How to wrap all elements that are next to each other and have the same class?

I would like to know how to wrap all elements that are next to each other and have the same class. 我想知道如何包装彼此相邻且具有相同类的所有元素。 .wrapAll() didn't work since it pushes the paragraph to the bottom. .wrapAll()无效,因为它会将段落推到底部。

Source: 资源:

 <div class="container"> <div class="group"></div> <div class="group"></div> <div class="group"></div> <p>Lorem ipsum dolor sit amet</p> <div class="group"></div> <div class="group"></div> <div class="group"></div> </div> 

Desired output: 所需的输出:

 <div class="container"> <div class="group-wrapper"> <div class="group"></div> <div class="group"></div> <div class="group"></div> </div> <p>Lorem ipsum dolor sit amet</p> <div class="group-wrapper"> <div class="group"></div> <div class="group"></div> <div class="group"></div> </div> </div> 

You will have to break it to groups between the non-matching elements. 您必须将其分解为不匹配元素之间的组。

$(function(){
    $.fn.reverse = [].reverse;
    var target = '.group', // the class of the elements to group
        invert = ':not(' + target + ')', // we create the invert to find the breakpoints
        wrap = '<div class="group-wrapper">', // what to wrap with
        breakpoints = $('.container > *'+invert); // find the breakpoints in our container

   breakpoints.each(function(){
        $(this).nextUntil(invert).wrapAll( wrap ); // get the matching elements efter this breakpoint and wrap them
    });

    breakpoints.first().prevUntil(invert).reverse().wrapAll( wrap ); // wrap the elements before the first breakpoint

});

Demo at http://jsfiddle.net/gaby/qz53fggd/ 演示位于http://jsfiddle.net/gaby/qz53fggd/

Here's one approach based on elements being children 这是一种基于元素是孩子的方法

var $container =$('.container');
function wrapGroup( target, $container){
    // wrap until next non group element
    var $groups = $container.children(target)
    if($groups.length){        
        $groups.first().nextUntil(':not('+target+')').andSelf().wrapAll('<div class="group-wrap">') 
    }
    // check if more group as children and do it again
    if($container.children(target).length){
        wrapGroup( target, $container);
    }    
}
//usage
wrapGroup('.group', $container);

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM