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

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

or

$(".myCheckBox").selected(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();

其他回答

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

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

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

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

这里有一种不使用jQuery的方法

函数addOrAttachListener(el,type,listener,useCapture){if(el.addEventListener){el.addEventListener(类型,监听器,useCapture);}否则如果(el.attachEvent){el.attachEvent(“on”+类型,监听器);}};addOrAttachListener(窗口,“加载”,函数(){var cbElem=文档.getElementById(“cb”);var rcbElem=文档.getElementById(“rcb”);addOrAttachListener(cbElem,“单击”,函数(){rcbElem.checked=cbElem.check;},假);},假);<label>单击我!<input id=“cb”type=“checkbox”/></label><label>反射:<input id=“rcb”type=“checkbox”/></label>

对于jQuery 1.6+

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

对于jQuery 1.5.x及以下版本

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

为了检查,

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

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

选中和取消选中

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);