如何使用juery获取checkbox的选中状态
使用jquery获取node节点的值非常方便,然后还是会有一些经常容易出错的地方。例如,我在使用jquery-1.4.2.min.js版本获取checkbox的选中状态的时候还好,可是使用1.7版本的时候就郁闷了。
1.6版本之前的:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>如何使用juery获取checkbox的选中状态</title> </head> <body> <input type="checkbox" id="check1" /> <input type="button" onclick="check1()" value="显示" /> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> function check1(){ //选中显示true,不选中显示false console.log($("#check1").attr("checked")); } </script> </body> </html>
1.6版本之后的
<script type="text/javascript"> function check1(){ //选中显示checked,不选中竟然显示undefined console.log($("#check1").attr("checked")); } </script>
如此看来,新版本的让人很不爽。原来是因为Attributes模块的变化是移除了attributes和properties之间模棱两可的东西,但是在jQuery社区中引起了一些混乱,因为在1.6之前的所有版本中都使用一个方法(.attr())来处理attributes和properties。但是老的.attr()方法有一些bug,很难维护。jQuery1.6.1对Attributes模块进行了更新,并且修复了几个bug。
注意:版本低于1.6时jquery不支持prop方法,会报Uncaught TypeError: $(...).prop is not a function
这时,对于版本大于等于1.6的jquery主要分为以下两种看法:
第一种:更倾向于使用新方法prop
1.对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
2.对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
第二种:更倾向于使用旧方法attr
1.添加属性名称该属性就会生效应该使用prop();
2.是有true,false两个属性使用prop();
3.其他则使用attr();
官方给出的不常用属性如下:
Attribute/Property | .attr() | .prop() |
---|---|---|
accesskey | √ | |
align | √ | |
async | √ | √ |
autofocus | √ | √ |
checked | √ | √ |
class | √ | |
contenteditable | √ | |
draggable | √ | |
href | √ | |
id | √ | |
label | √ | |
location ( i.e. window.location ) | √ | √ |
multiple | √ | √ |
readOnly | √ | √ |
rel | √ | |
selected | √ | √ |
src | √ | |
tabindex | √ | |
title | √ | |
type | √ | |
width ( if needed over .width() ) | √ |
由此可见,只有少数属性需要注意。无论哪种看法都可以,只要能正确获取到值即可。
本文地址:http://blog.zhengshuiguang.com/js/jquery-attr.html
转载随意,但请附上文章地址:-)
评论已关闭