jQuery判断复选框checkbox的选中状态

通过jQuery设置复选框为选中状态

复选框

<input type="checkbox"/>

错误代码:

$("input").attr("checked","checked");

设置以后checkbox变成选中状态,用Chrome调试看了一下,checkbox中确实有checked属性,而且值为checked,根据W3C的表单规范,checked属性是一个布尔属性,这意味着只要该 attribute 存在,即使它没有值,或是一个空字符串,该属性对应的 property 默认就是 true,也就是说和attribute的值没有关系。但是一旦通过 prop 将 property 设置为false,则使用 attr 将无法使该 checkbox 改变为选中状态。

正确代码:

$("input").prop("checked",true);

设置后复选框为选中状态了。

原因:

attributes(属性) 和 properties(特性) 之间的差异在特定情况下是很重要的。

jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。

从 jQuery 1.6 开始, .prop()方法返回 property 的值,而 .attr() 方法返回 attributes 的值。

以下推荐的是兼容浏览器的三种写法,判断 checkbox 元素的 checked 属性是否为"真" (是否被选中),elem是 JavaScript 对象:

if ( $(elem).prop("checked") ){} 
if ( $(elem).is(":checked") ){}
if ( elem.checked ) {}

代码示例:

 1 <html> 
 2     <head> 
 3         <title></title> 
 4         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5         <script type="text/javascript" src="jquery-3.1.1.min.js"></script> 
 6     </head> 
 7     <body> 
 8         <div>
 9             <input type="button" value="点击1" onclick="add1();" />
10             <input type="button" value="点击2" onclick="add2();" />
11             <input type="button" value="点击3" onclick="add3();" />
12             <input type="checkbox" id="myinput" /> 
13         </div> 
14     </body>
15     <script type="text/javascript"> 
16         //添加选中和未选中状态
17         function add1(){
18             if($("#myinput").prop("checked")){
19                 $("#myinput").prop("checked",false);
20             }else{
21                 $("#myinput").prop("checked",true);
22             }
23             
24         }
25         function add2(){
26             if($("#myinput").is(":checked")){
27                 $("#myinput").prop("checked",false);
28             }else{
29                 $("#myinput").prop("checked",true);
30             }
31         }
32         function add3(){
33             if(document.getElementById("myinput").checked){
34                 $("#myinput").prop("checked",false);
35             }else{
36                 $("#myinput").prop("checked",true);
37             }
38         }
39     </script>
40 </html>
原文地址:https://www.cnblogs.com/wbxk/p/6138312.html