jQuery - putting a closing div after the current this element?
I'm trying to dynamically segment each generated-label and hardcoded input pair with div tag's. I seem to be able to get the div to surround the label (see source below), but I'd like the div to surround the input as well.
This has the div surround the input only:
<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" /> &开发者_如何学运维lt;/form>
http://jsfiddle.net/RM5wG/12/
Rather than having div's just around the label, I'd like to figure out how to get jQuery to append div's to the entire pair, i.e., final outlook like:
<div> <label>...</label> <input /> </div>
You can do it using .wrapAll()
like this:
$(function(){
$("#sg1 input").each(function(){
$(this).wrap('<div></div>').parent()
.prepend('<label for="'+ this.name +'">'+$(this).val()+'</label>');
});
});
You can check it out here. Or, closer to your original:
$(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, what we're doing is adding the label before the input, then grabbing it and adding it to the collection with .prev()
and .andSelf()
, then we're just calling a .wrapAll()
on both elements.
$("input #sg1").each(function(){
$(this).wrap("<div></div>");
$("<label for=\""+$(this).attr("name")+"\">"+$(this).val()+"</label>").insertBefore(this);
}
精彩评论