如何前置或包装每个标签和div?

问题描述 投票:1回答:4

我有这个标签序列和divs,我需要包围每组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>
javascript jquery each
4个回答
1
投票

您可以通过迭代标签并包装/附加每个标签来实现:

$('label').each(function() {
    $(this).wrap('<div class="l"/>').parent().next().appendTo($(this).parent());
});

但是:ぁzxswい


2
投票

假设这个标记总是这样:

http://jsfiddle.net/UNyeQ/1/

你可以放弃$("label").each(function () { $(this).next("div").andSelf().wrapAll("<div>"); }); "div",但它可以防止其他元素妨碍你。

.next


2
投票

或者,使用http://jsfiddle.net/UNyeQ/3/

.wrapAll()

$("label").each(function(){ var $this = $(this); $this.add($this.next()).wrapAll("<div class='1'/>"); });


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的孩子,否则。

© www.soinside.com 2019 - 2024. All rights reserved.