jquery 1.6+ 获取checkbox的checked属性总是checked

项目中用的jquery1.9 今天需要检测一个checkbox的选中状态,想当然的用 .attr("checked") ,结果发现,无论是否选中,这个值都是 undefined 未定义。

折腾了半天,无奈,只能取jq官网看看文档,发现有这么一段说明

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()method.

注意最后两句话,说什么.attr() 不能用于普通对象,数组,窗口,文档什么玩意的,要重新获取改变dom属性,用.prop()方法。

ok,虽然不太明白它说的具体含义是什么,但是看到.prop方法姑且一试吧,结果还真可以,若选中则返回true否则返回false。

代码贴上来,有兴趣可自行测试:

01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03     <head>
04         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
05         <script>
06             $(function(){
07                 $("#clk").click(function(){
08                     alert($("#ckb").prop("checked"));
09                 })
10             })
11         </script>
12     </head>
13     <body>
14         <input type="button" value="click" id="clk">
15         <input type="checkbox" id="ckb"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值