1

我想知道如何包装彼此相邻且具有相同类的所有元素。.wrapAll()没有用,因为它将段落推到了底部。

来源:

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

期望的输出:

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

4

2 回答 2

5

您必须将其分解为不匹配元素之间的组。

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

});

演示在http://jsfiddle.net/gaby/qz53fggd/

于 2015-01-26T18:40:32.557 回答
1

这是一种基于子元素的方法

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

于 2015-01-26T18:40:08.580 回答