jQuery创建已选中的复选框

3
如何使用jQuery创建已选中的复选框元素?
我尝试过以下代码:
$('<input>', {
    type:"checkbox",
    "checked":"checked"
});

并且

var input = $('<input>', {
    type:"checkbox"
});
input.attr('checked',true);

这些没有起作用。 在将复选框添加到元素后,它仍然未被选中。

1个回答

10
你需要将它们附加到文档中。

例如:

$('<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');

如何绘制未选中的复选框。 - ozil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接