如何使用jquery创建选中的复选框元素?
我试过了。
$('<input>', {
type:"checkbox",
"checked":"checked"
});
和
var input = $('<input>', {
type:"checkbox"
});
input.attr('checked',true);
这些都不起作用。 附加到元素后,该复选框保持未选中状态。
答案 0 :(得分:9)
您必须将它们附加到文档。
例如:
$('<input>', {
type:"checkbox",
"checked":"checked"
}).appendTo('body'); // instead of body you can use any valid selector
// to your target element to which you want to
// append this checkbox
代码
$('<input>', {
type:"checkbox",
"checked":"checked"
});
只需创建一个元素,但不要将其附加到DOM。要将其附加到DOM,您必须使用 append()
/ appendTo()
/ html()
等任何一种方法。
如果是第二个片段:
var input = $('<input>', {
type:"checkbox"
});
input.attr('checked',true);
$('#target_container').append(input);
// Or
input.appendTo('#target_container');