手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >jquery checkbox无法用attr()二次勾选问题的解决方法
jquery checkbox无法用attr()二次勾选问题的解决方法
摘要:今晨,漂亮的测试妹妹提了个奇怪的bug,说我一功能checkbox时隐时现,比如第一次打开有勾选,第n次打开可能就不选了。想到与美女有亲密接...

今晨,漂亮的测试妹妹提了个奇怪的bug,说我一功能checkbox时隐时现,比如第一次打开有勾选,第n次打开可能就不选了。

想到与美女有亲密接触机会,马上鸡动起来。

经过偶层层抽次剥茧(da da jiang you),终于知道了原因:attr()在二次选中勾选框时,失效。

比如,如下HTML页面,一点【选中】、二点【取消选中】、三点【选中】,瞧,不行了呗。

1.html

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>prop demo</title> <style> img { padding: 10px; } div { color: red; font-size: 24px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <input type="checkbox" checked="checked"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox" checked="checked"> <script> $( "input[type='checkbox']" ).prop( "checked", function( i, val ) { return !val; }); </script> </body> </html>

解决方案,是使用prop()替换attr()方法(在Jquery1.6以上),如下代码:

2.html

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Attr checked</title> <script type="text/javascript" src="./js/jquery-1.11.2.js"></script> <script type="text/javascript"> function switchChecked(flag) { $("input[type='checkbox']").prop('checked', flag); } </script> </head> <body> <input type="checkbox" /> <input type="button" value="选中"> <input type="button" value="取消选中"> </body> </html>

关于官方文档,见:http://api.jquery.com/attr/

或者http://api.jquery.com/prop/

摘抄如下:“As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.”

以上这篇jquery checkbox无法用attr()二次勾选问题的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持查字典教程网。

【jquery checkbox无法用attr()二次勾选问题的解决方法】相关文章:

jQuery fancybox在ie浏览器下无法显示关闭按钮的解决办法

jQuery仿gmail实现fixed布局的方法

iscroll.js的上拉下拉刷新时无法回弹的解决方法

js控制excel打印完美解决方案

png在IE6 下无法透明的解决方法汇总

判断Checkbox和Radio的一种方法

浅谈jQuery中replace()方法

判断checkbox选择的个数 多浏览器

JQuery boxy插件在IE中边角图片不显示问题的解决

jQuery基于图层模仿五星星评价功能的方法

精品推荐
分类导航