Jquery1.6版本后attr的变化,灰常委屈
来源:广州中睿信息技术有限公司官网
发布时间:2012/10/21 23:25:16 编辑:admin 阅读 254
基于上次发表的Jquery获取checkbox的checked问题,从大家的评论中得到了答案,原因是Jquery1.6版本后attr给改了,悲剧的我不知道,给耍了半天。认真地去看了官方的最新文档,当

基于上次发表的 Jquery 获取checkbox的checked问题 ,从大家的评论中得到了答案,原因是Jquery1.6版本后 attr 给改了,悲剧的我不知道,给耍了半天。

认真地去看了官方的最新文档,当中有这样的一段话 = =!

 

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

elem.checked true (Boolean) Will change with checkbox state
$(elem).prop("checked") true (Boolean) Will change with checkbox state
elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state

 


可见,给YIN了吧。下面发个改动后的效果:
jquery1.6+版本:

 

 1 <!DOCTYPE html> 
2 <html>
3 <head>
4 <style>
5 p { margin: 20px 0 0 }
6 b { color: blue; }
7 </style>
8 <script src="../js/jquery-1.7.min.js"></script>
9 </head>
10 <body>
11
12 <input id="check1" type="checkbox" checked="checked">
13 <label for="check1">Check me</label>
14 <p></p>
15
16 <script>
17 $("input").change(function() {
18 var $input = $(this);
19 $("p").html(".attr('checked'): <b>" + $input.attr('checked') + "</b><br>"
20 + ".prop('checked'): <b>" + $input.prop('checked') + "</b><br>"
21 + ".is(':checked'): <b>" + $input.is(':checked') ) + "</b>";
22 }).change();
23 </script>
24
25 </body>
26 </html>

勾选后输出:
attr('checked'): checked
.prop('checked'): true
.is(':checked'): true

联系我们CONTACT 扫一扫
愿景:成为最专业的软件研发服务领航者
中睿信息技术有限公司 广州•深圳 Tel:020-38931912 务实 Pragmatic
广州:广州市天河区翰景路1号金星大厦18层中睿信息 Fax:020-38931912 专业 Professional
深圳:深圳市福田区车公庙有色金属大厦509~510 Tel:0755-25855012 诚信 Integrity
所有权声明:PMI, PMP, Project Management Professional, PMI-ACP, PMI-PBA和PMBOK是项目管理协会(Project Management Institute, Inc.)的注册标志。
版权所有:广州中睿信息技术有限公司 粤ICP备13082838号-2