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

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

or

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

这样的事情存在吗?


当前回答

这可能会帮助某人。

HTML5

 <input id="check_box" type="checkbox" onclick="handleOnClick()">

JavaScript。

  function handleOnClick(){

      if($("#check_box").prop('checked'))
      {        
          console.log("current state: checked");
      }
      else
      {         
          console.log("current state: unchecked");
      }    
 }

其他回答

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

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

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

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

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

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

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

2019年1月编辑

您可以使用:.prop(propertyName)-添加的版本:1.6

p{margin:20px 0 0;}b{颜色:红色;}标签{颜色:红色;}<!doctype html><html lang=“en”><head><meta charset=“utf-8”><script src=“https://code.jquery.com/jquery-1.10.2.js“></script></head><body><input id=“check1”type=“checkbox”checked=“checked”><label for=“check1”>检查此处</label><p></p><脚本>$(“input”).change(函数){var$input=$(this);$(“p”).html(“.attr(\”checked\“):<b>”+$input.attr“(”checked“)+”</b><br>“+“.prop(\”checked\“):<b>”+$input.prop(”checked“)+“</b><br>”+“.is(\”:checked \“):<b>”+$input.is(“:checked”)+“</b>”);}).change();</script></body></html>

论角度框架

示例1

在.html文件中

<input type="checkbox" (change)="toggleEditable($event)">

在.ts文件中

toggleEditable(event) {
     if ( event.target.checked ) {
         this.contentEditable = true;
    }
}

示例2

在.html文件中

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkAction(isChecked ? 'Action1':'Action2')" />

如果您使用ASP.NET MVC,生成许多复选框,然后必须使用JavaScript选择/取消选择所有选项,您可以执行以下操作。

HTML

@foreach (var item in Model)
{
    @Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}

JavaScript

function SelectAll() {       
        $('input[id^="ProductId_"]').each(function () {          
            $(this).prop('checked', true);
        });
    }

    function UnselectAll() {
        $('input[id^="ProductId_"]').each(function () {
            $(this).prop('checked', false);
        });
    }

我们可以使用elementObject和jQuery来检查属性:

$(objectElement).attr('checked');

我们可以在所有jQuery版本中使用它,而不会出现任何错误。

更新:Jquery 1.6+具有替换attr的新prop方法,例如:

$(objectElement).prop('checked');