【问题标题】:wrapAll jQuery problemwrapAll jQuery 问题
【发布时间】:2009-10-07 05:53:58
【问题描述】:

我需要将三个 div 包装成一个,但是这组三个 div 在代码中重复了好几次。也许我的 HTML 会解释:

<div class="one" />
<div class="two" />
<div class="three" />

<div class="one" />
<div class="two" />
<div class="three" />

我想要实现的是:

<div class="wrap">
  <div class="one" />
  <div class="two" />
  <div class="three" />
</div>

<div class="wrap">
  <div class="one" />
  <div class="two" />
  <div class="three" />
</div>

这是将所有内容包装到一个 div 中:

$('.one, .two, .three').wrapAll('<div class="wrap" />')

如何将组分开包装?

【问题讨论】:

  • 所以每组div.one div.two div.three 都需要用div.wrap 包裹?

标签: javascript jquery html


【解决方案1】:
$(function(){
    var all = $('.one, .two, .three');
    for(i=0; i<all.length; i+=3){
        all.slice(i,i+3).wrapAll('<div class="wrap" />');
    }
});

查看实际操作:http://jsbin.com/uqosa/

顺便说一句,&lt;div class="one" /&gt; 在 Firefox 上对我不起作用,我不得不用 &lt;/div&gt; 关闭它们。

【讨论】:

    【解决方案2】:

    试试这个:

    $('div.one').each(function() {
        var wrap = $(this).wrap('<div class="wrap"></div>').parent();
        wrap.next('div.two').appendTo(wrap);
        wrap.next('div.three').appendTo(wrap);
    });
    

    【讨论】:

      【解决方案3】:

      这将起作用:

      $(function() {
          var $ones = $('div.one');
          var $twos = $('div.two');
          var $threes = $('div.three');
      
          $ones.each(function(idx) {
              $('<div class="wrap"></div>')
                  .append($ones.eq(idx))
                  .append($twos.eq(idx))
                  .append($threes.eq(idx))
                  .appendTo('body');
          });
      });
      

      【讨论】:

        【解决方案4】:

        在我看来,这应该工作:

        $('.one').each(function() {
            var wrap = $('<div>').addClass('wrap'), two = $(this).next(), three = $(two).next();
            $(this).after(wrap).appendTo(wrap)
            two.appendTo(wrap), three.appendTo(wrap)
        });
        

        【讨论】:

        • 更新了我的答案几次。
        【解决方案5】:
        $.fn.matchUntil = function(expr) {
            var match = [];
            this.each(function(){
                match = [this];
                for ( var i = this.nextSibling; i; i = i.nextSibling ) {
                    if ( i.nodeType != 1 ) { continue; }
                    if ( $(i).filter(expr).length > 0 ) { break; }
                    match.push( i );
                }
            });
            return this.pushStack( match );
        };
        

        用法:

        $(".one").each( function() {
            $(this).matchUntil(".one").wrapAll("<div class='wr'></div>");
        })
        

        它只是 http://docs.jquery.com/JQuery_1.2_Roadmap#.nextUntil.28.29_.2F_.prevUntil.28.29 的修改版本,它似乎不适用于新的 jQuery。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-06
          • 2014-07-17
          • 2016-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多