您的位置:首页 > Web前端 > JQuery

使用jQuery判断checkbox是否被选中

2016-12-06 17:13 399 查看
通过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.checked ) {}

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

if ( $(elem).is(":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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: