jQuery - 在当前这个元素之后放一个结束div?

时间:2010-08-12 00:30:33

标签: jquery

我正在尝试使用div标签动态分段每个生成标签和硬编码输入对。我似乎能够让div围绕标签(参见下面的源代码),但我也希望div能够包围输入。

这只有div环绕输入:


​<script>
$(document).ready(function(){
    $("#sg1 input").each(function(){
    $("​<div>​<label for=\""+$(this).attr("name")+"\">"+$(this).val()+"​</label>")
.insertBefore(this);
    });
});
​</script>

​<form id="sg1">
    ​<input name="member1" id="member1" value="jack" />
    ​<input name="member2" id="member2" value="carter" />
    ​<input name="member3" id="member3" value="jackson" />
    ​<input name="member4" id="member4" value="tielk" />    
​</form>​

http://jsfiddle.net/RM5wG/12/

我不想在标签周围使用div,而是想弄清楚如何让jQuery将div添加到整个对中,即最终的展望如下:

​<div>
​<label>...​</label>
​<input />
​</div>

2 个答案:

答案 0 :(得分:4)

你可以使用.wrapAll()这样做:

$(function(){
  $("#sg1 input").each(function(){
    $(this).wrap('<div></div>').parent()
           .prepend('<label for="'+ this.name +'">'+$(this).val()+'</label>');
  });
});

You can check it out here。或者,更接近您原来的:

$(function(){
    $("#sg1 input").each(function(){
    $(this).before('<label for="'+ this.name +'">' + $(this).val() + '</label>')
           .prev().andSelf().wrapAll('<div></div>');
    });
});

You can give it a try here,我们正在做的是在输入之前添加标签,然后抓住它并使用.prev().andSelf()将其添加到集合中,然后我们只是调用两个元素都有.wrapAll()

答案 1 :(得分:1)

$("input #sg1").each(function(){
    $(this).wrap("<div></div>");
    $("​​<label for=\""+$(this).attr("name")+"\">"+$(this).val()+"​</label>").insertBefore(this);
}