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

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

or

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

这样的事情存在吗?


当前回答

Use:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

如果要检查是否选中复选框:

$('.myCheckbox').is(':checked');

其他回答

您还可以使用新方法扩展$.fn对象:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

然后你可以这样做:

$(":checkbox").check();
$(":checkbox").uncheck();

或者,如果您使用其他使用这些名称的库,您可能希望为它们提供更多的唯一名称,如mycheck()和myuncheck()。

$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

最后一个将激发复选框的单击事件,其他的则不会。因此,如果您在onclick事件中为要激发的复选框设置了自定义代码,请使用最后一个。

当您选中以下复选框时:;

$('.className').attr('checked', 'checked')

这可能还不够。您还应调用以下函数:;

$('.className').prop('checked', 'true')

尤其是在删除复选框选中属性时。

我无法通过以下方式实现:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

true和false都会选中该复选框。对我有用的是:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking

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

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

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