通过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 ) {}

代码示例:

 <html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
</head>
<body>
<div>
<input type="button" value="点击1" onclick="add1();" />
<input type="button" value="点击2" onclick="add2();" />
<input type="button" value="点击3" onclick="add3();" />
<input type="checkbox" id="myinput" />
</div>
</body>
<script type="text/javascript">
//添加选中和未选中状态
function add1(){
if($("#myinput").prop("checked")){
$("#myinput").prop("checked",false);
}else{
$("#myinput").prop("checked",true);
} }
function add2(){
if($("#myinput").is(":checked")){
$("#myinput").prop("checked",false);
}else{
$("#myinput").prop("checked",true);
}
}
function add3(){
if(document.getElementById("myinput").checked){
$("#myinput").prop("checked",false);
}else{
$("#myinput").prop("checked",true);
}
}
</script>
</html>

最新文章

  1. 深入理解JS的闭包
  2. 使用Wireshark 查看查找未被过滤端口
  3. Struts2中的ActionContext、OGNL及EL的使用
  4. struts 中 s:iterator 使用注意事项
  5. ab apache Benchmarking中链接的写法 记得加上/
  6. Redis实战之Redis + Jedis[转]
  7. VPN ,Bypass the FIrewall
  8. 【HDOJ】1732 Push Box
  9. php 实现同一个账号同时只能一个人登录
  10. 高性能 TCP &amp;amp; UDP 通信框架 HP-Socket v3.2.3 正式公布
  11. [补档]暑假集训D6总结
  12. MT【326】曲线中的爱恨情仇
  13. vue-列表嵌套
  14. 04-TypeScript中的方法新功能(上)
  15. linux-阿里云仓库搭建-搭建本地仓库-yum
  16. POJ1185 状压dp(二进制//三进制)解法
  17. Linux配置Python默认版本
  18. Metasploit services
  19. 阿里云内网和公网NTP服务器和其他互联网基础服务时间同步服务器
  20. ECCV 2018 | 旷视科技提出统一感知解析网络UPerNet,优化场景理解

热门文章

  1. 通过adb启动app应用
  2. HTTP 中 GET 与 POST 的区别
  3. html css col-md-offset
  4. json and pickle 序列化
  5. git配置正确且权限已开但是pull或push提示无权限
  6. mysql 查询结果集按照指定的字段值顺序排序
  7. SpringCloud Feign context-path踩到的坑
  8. http://ctf.bugku.com/challenges#%E9%80%86%E5%90%91%E5%85%A5%E9%97%A8:bugku--逆向入门
  9. IIS7发布asp.net mvc提示404.0
  10. zabbix3.x自动发现主机