浅谈jQuery中的checkbox问题(2)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> function checkAll(name) { var el = document.getElementsByTagName('input'); var len = el.length; for(var i=0; i<len; i++) { if((el[i].type=="checkbox") && (el[i].name==name)) { el[i].checked = true; } } } function clearAll(name) { var el = document.getElementsByTagName('input'); var len = el.length; for(var i=0; i<len; i++) { if((el[i].type=="checkbox") && (el[i].name==name)) { el[i].checked = false; } } } </script> <input type="checkbox" value="" /> 字母全选开关 <input type="checkbox" value="a" /> a <input type="checkbox" value="b" /> b <input type="checkbox" value="c" /> c <input type="checkbox" value="d" /> d <input type="checkbox" value="e" /> e <input type="checkbox" value="f" /> f <input type="checkbox" value="g" /> g <br> <input type="checkbox" value="" /> 数字全选开关 <input type="checkbox" value="1" /> 1 <input type="checkbox" value="2" /> 2 <input type="checkbox" value="3" /> 3 <br><br> <input type="button" value="选择所有的字母" /> <input type="button" value="清空选中的字母" /> <br><br> <input type="button" value="选择所有的数字" /> <input type="button" value="清空选中的数字" /> </body> </html>

最后插入attr()与prop()的区别:

jquery1.6中新加了一个方法prop(),官方解释只有一句话:获取在匹配的元素集中的第一个元素的属性值。

大家都知道有的浏览器只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked",比如用attr("checked")获取checkbox的checked属性时选中的时候可以取到值,值为"checked"但没选中获取值就是undefined。

jq提供新的方法“prop”来获取这些属性,就是来解决这个问题的,以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。

那么,什么时候使用attr(),什么时候使用prop()?

1.添加属性名称该属性就会生效应该使用prop();

2.是有true,false两个属性使用prop();

3.其他则使用attr();

项目中jquery升级的时候大家要注意这点!

以下是官方建议attr(),prop()的使用:

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())      

以上这篇浅谈jQuery中的checkbox问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzxggj.html