你很幸运,这正是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
之前first
s!):
var current;
$(".first, .second").each(function() {
var $this = $(this);
if ($this.hasClass('first')) {
current = $('<div class="container"></div>').insertBefore(this);
}
current.append(this);
});
实例 | Source