如何用不同的类名包裹DIV标签? [复制]

2023-12-01

复制:
如何将父元素添加到一组段落中?

我在文档中重复了以下 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>

...

我如何用 jQuery 包装 Div 以获得像这样的 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>

...

你很幸运,这正是wrapAll is for:

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

实例 | Source


您的编辑markedly改变问题。如果您只需要执行上述操作within一些包含块,您可以循环遍历包含块并应用wrapAll只针对其内容。您需要一种方法来确定您想要对 div 进行分组的方式,而您在问题中尚未指定。

如果 div 周围有某种容器,您可以这样做:

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

在该示例中,我假设 div 位于具有该类的容器内"block".

实例 | Source

如果没有结构性的方法来识别它们,你就必须采用其他方法。例如,在这里我们假设任何时候我们看到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>');
}

实例 | Source

这有效是因为$()给你的元素文件顺序,因此,如果我们按顺序循环遍历它们,将它们保存起来,然后每当看到新的时就将之前的包裹起来first(当然,最后清理干净),你就得到了想要的结果。

或者这是做同样事情的另一种方法,它不使用wrapAll。它依赖于first匹配元素是first (so no second之前firsts!):

var current;

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

实例 | Source

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用不同的类名包裹DIV标签? [复制] 的相关文章

随机推荐