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

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

or

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

这样的事情存在吗?


当前回答

你可以这样做,如果你有身份证来检查它

document.getElementById('ElementId').checked=false

这个要取消选中

document.getElementById('ElementId').checked=真

其他回答

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

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

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

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

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

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

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

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

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

正如@livefree75所说:

jQuery 1.5.x及以下版本

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

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

但是在jQuery的新版本中,我们必须使用如下内容:

jQuery 1.6+

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

然后你可以这样做:

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

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

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

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

如果您考虑使用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
}