3

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

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

...
4

2 回答 2

17

你很幸运,这正是wrapAll它的用途:

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

实例| 来源


您的编辑明显改变了问题。如果您只需要在某些包含块中执行上述操作,则可以循环遍历包含块并wrapAll仅应用于它们的内容。您需要一种方法来确定您想要对 div 进行分组的方式,而您没有在问题中指定。

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

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

在该示例中,我假设 div 位于带有 class 的容器中"block"

实例| 来源

如果没有结构性的方法来识别它们,则必须以其他方式进行。例如,在这里我们假设任何时候我们看到 a 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

Or here's another way to do that same thing, which doesn't use wrapAll. It relies on the first matched element being a first (so no seconds before firsts!):

var current;

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

Live Example | Source

于 2012-12-14T11:26:31.393 回答
3
$('div').wrapAll('<div class="container" />');

会这样做,但这也会包装任何其他div,所以也许:

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

更好。

于 2012-12-14T11:26:07.487 回答