-->

演示如何用不同的类名称DIV标签? [重复](How to wrap DIV tags with

2019-07-05 06:54发布

重复:
我怎样才能父元素添加到组段?

我已经重复了文档中的下列HTML块

<!-- first block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

<!-- second block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

...

我如何包装的div使用jQuery获得这样生成的HTML ...

<!-- first block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

<!-- second block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

...

Answer 1:

你很幸运,这正是wrapAll是:

$(".first, .second").wrapAll('<div class="container"></div>');

活生生的例子 | 资源


您编辑显着变化的问题。 如果你只需要一些内部包含块做到上面,你可以通过包含块循环和应用wrapAll只有其内容。 你需要一种方法来确定你所希望的方式将你的div,你有没有在问题中指定。

如果div的有某种他们周围的容器,你可以这样做:

$(".block").each(function() {
  $(this).find(".first, .second").wrapAll('<div class="container"></div>');
});

在该例子中,我假定的div是与类一容器内"block"

活生生的例子 | 资源

如果有,以确定他们没有结构的方式,你必须做一些其他的方式。 举例来说,在这里,我们假定我们看到了一个任何时候做到这一点first ,我们应该停止分组:

var current = $();

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    doTheWrap(current);
    current = $();
  }
  current = current.add(this);
});
doTheWrap(current);

function doTheWrap(d) {
  d.wrapAll('<div class="container"></div>');
}

活生生的例子 | 资源

这工作因为$()为您提供了文档顺序的元素,所以如果我们循环,以便他们,为他们节省起来,然后包装起来以前的,每当我们看到一个新的first (当然,在最后清理),你得到想要的结果。

或者还有一种方法做同样的事情,不使用wrapAll 。 它依靠第一匹配元件是在first (所以没有second S前first小号!):

var current;

$(".first, .second").each(function() {
  var $this = $(this);
  if ($this.hasClass('first')) {
    current = $('<div class="container"></div>').insertBefore(this);
  }
  current.append(this);
});

活生生的例子 | 资源



Answer 2:

$('div').wrapAll('<div class="container" />');

将做到这一点,但也将包装任何其他的div所以可能:

$('.first, .second').wrapAll('<div class="container" />'); 

更好。



文章来源: How to wrap DIV tags with different class names? [duplicate]