我需要一个简单的jQuery代码,它会在每个单选按钮或复选框旁边添加一个空标签标签
例如:
$('input[type="radio"]').next().add("<label for="radio"></label>");
$('input[type="checkbox"]').next().add("<label for="checkbox"></label>");
我该如何做到这一点?
感谢。
答案 0 :(得分:5)
您需要使用after来完成此操作。此外,您还希望标签的for
为其引用的id
。
$('input[type="checkbox"]').each(function() {
var cb = $(this);
cb.after($("<label />")
.attr("for", cb.attr("id")) );
});
你说你想要空标签,但为了以防万一,如果你想让标签显示他们旁边的复选框的价值,这应该是这样的:
$('input[type="checkbox"]').each(function() {
var cb = $(this);
cb.after($("<label />")
.attr("for", cb.attr("id"))
.text(cb.val()) );
});
答案 1 :(得分:2)
$('input[type="radio"]').after("<label for='radio'></label>");
$('input[type="checkbox"]').after("<label for='checkbox'></label>");
答案 2 :(得分:1)
您想使用jQuery函数.after()
$('input[type="radio"]').after('<label for="radio"></label>');
$('input[type="checkbox"]').after('<label for="checkbox"></label>');
但是,如果您希望标签定位正确的元素,则需要执行此操作:
$('input[type="radio"], input[type="checkbox"]').each( function() {
var id = $(this).attr( "id" );
$(this).after('<label for="' + id + '"></label>');
} );
您需要将元素的ID放在标签标记
的for
属性中
答案 3 :(得分:0)
$(':radio, :checkbox').each(function () {
$(this).before('<label for="' + this.id + '"></label>');
});