jquery创建选中复选框

Ham*_*aza 2 jquery

如何使用jquery创建选中的复选框元素?

我试过了.

$('<input>', {
    type:"checkbox",
    "checked":"checked"
});
Run Code Online (Sandbox Code Playgroud)

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

这些都不起作用.附加到元素后,该复选框保持未选中状态.

the*_*dox 9

你必须将它们附加到Document.

例如:

$('<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
Run Code Online (Sandbox Code Playgroud)

代码

$('<input>', {
    type:"checkbox",
    "checked":"checked"
});
Run Code Online (Sandbox Code Playgroud)

只需创建一个元素,但不要将其附加到DOM.为了将它附加到DOM,您必须使用append()/ appendTo()/ html()etc任何一种方法.

如果是第二个片段:

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

$('#target_container').append(input);

// Or

input.appendTo('#target_container');
Run Code Online (Sandbox Code Playgroud)