我想这样做,使用jQuery勾选复选框:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

这样的事情存在吗?


当前回答

$(".myCheckBox").prop("checked","checked");

其他回答

你可以的

$('.myCheckbox').attr('checked',true) //Standards compliant

or

$("form #mycheckbox").attr('checked', true)

如果在onclick事件中有要激发的复选框的自定义代码,请改用此代码:

$("#mycheckbox").click();

可以通过完全删除该属性来取消选中:

$('.myCheckbox').removeAttr('checked')

您可以这样选中所有复选框:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});

如果您考虑使用vanilla js而不是jquery,那么有一个解决方案:

//for one element: 
document.querySelector('.myCheckBox').checked = true /* or false */ //will select the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
checkbox.checked = true //or false
}

这将选择具有指定属性且值包含给定子字符串“ckbItem”的元素:

$('input[name *= ckbItem]').prop('checked', true);

它将选择名称属性中包含ckbItem的所有元素。

如jQuery文档所述,请注意Internet Explorer 9之前的Internet Explorer内存泄漏:

在版本9之前的Internet Explorer中,使用.prop()设置DOM元素属性设置为除简单基元值以外的任何值如果属性为在移除DOM元素之前未移除(使用.removeProp())从文档中删除。在没有内存的情况下安全地设置DOM对象的值泄漏,请使用.data()。

$(".myCheckBox").prop("checked","checked");