【问题标题】:How to wrap all elements that are next to each other and have the same class?如何包装彼此相邻且具有相同类的所有元素?
【发布时间】:2015-03-25 05:32:38
【问题描述】:

我想知道如何包装彼此相邻且具有相同类的所有元素。 .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>

【问题讨论】:

  • 对于这个特定的结构?或者在其他情况下也可以工作?
  • 我需要一个适用于所有情况的解决方案。组之间可能存在除单个段落之外的其他元素。

标签: javascript jquery grouping wrapall


【解决方案1】:

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

$(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/的演示

【讨论】:

  • 为什么第一个包装器中的顺序会发生变化?似乎 prevUntil/wrapAll 组合是以相反的顺序添加元素或其他东西
  • 我猜 prevUntil 从下往上构建集合,然后 wrapAll 的索引被反转
  • @charlietfl 我从断点开始。因此,如果第一个断点之前有元素,它们将被该特殊情况捕获。所有其他都由.each() 部分处理
  • 对,我遵循逻辑,有趣的是第一组中元素的反转 3-2-1 而不是 1-2-3
  • @charlietfl blush.. 我什至没有注意到这种行为。 prevAllprevUntil 返回最接近最远顺序的匹配元素。更新了解决此问题的答案。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2020-07-22
    • 2016-10-31
    • 2022-07-07
    • 2014-05-06
    • 2015-01-19
    相关资源
    最近更新 更多