Duplicate:
How can I add a parent element to a group of paragraph?
我在文档中重复了以下 HTML block
<!-- 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
用于:
$(".first, .second").wrapAll('<div class="container"></div>');
Live Example | Source
您的编辑显着改变了问题。如果您只需要在某些包含 block 内 执行上述操作,您可以遍历包含 block 并将wrapAll
仅应用于它们的内容。你需要一种方法来确定你想要对你的 div 进行分组的方式,你没有在问题中指定。
如果 div 周围有某种容器,您可以这样做:
$(".block").each(function() {
$(this).find(".first, .second").wrapAll('<div class="container"></div>');
});
在那个例子中,我假设 div 在类 "block"
的容器中。
Live Example | 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>');
}
Live Example | Source
这是可行的,因为 $()
以文档顺序 为您提供元素,因此如果我们按顺序遍历它们,保存它们,然后结束前一个每当我们看到一个新的 first
时(当然,在最后清理),你就会得到想要的结果。
或者这是做同样事情的另一种方法,它不使用 wrapAll
。它依赖于 first 匹配元素是 first
(因此 first
之前没有 second
!):
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