我有这个标签序列和div
s,我需要包围每组1个标签+ 1 div另一个div。我知道我必须使用.each和.wrap
或.prepend
我需要帮助。我怎样才能做到这一点?
HTML:
<label>label</label>
<div>text</div>
<label>label</label>
<div>text</div>
Here I have set a jsFiddle demo.
结果应该是这样的:
<div class="1">
<label>label</label>
<div>text</div>
</div>
<div class="1">
<label>label</label>
<div>text</div>
</div>
您可以通过迭代标签并包装/附加每个标签来实现:
$('label').each(function() {
$(this).wrap('<div class="l"/>').parent().next().appendTo($(this).parent());
});
但是:ぁzxswい
假设这个标记总是这样:
http://jsfiddle.net/UNyeQ/1/
你可以放弃$("label").each(function () {
$(this).next("div").andSelf().wrapAll("<div>");
});
的"div"
,但它可以防止其他元素妨碍你。
.next
或者,使用http://jsfiddle.net/UNyeQ/3/。
.wrapAll()
$("label").each(function(){
var $this = $(this);
$this.add($this.next()).wrapAll("<div class='1'/>");
});
这可能不是最有效的方法,但经过多次不同的尝试,这就是我提出的:
See it here.
我试过的其他所有东西都会选择标签和div分别迭代它们,所以它不会在同一个div下配对。将$('label').each(function() {
var next = $(this).nextAll('div')[0];
$(this).wrap('<div class="new" />').append(next);
});
保存到变量的额外工作是因为div
对同一父母的兄弟姐妹进行操作 - 大概是nextAll()
在评估label
之前将成为新div
的孩子,否则。