jquery checkbox无法用attr()二次勾选问题的解决方法
今晨,漂亮的测试妹妹提了个奇怪的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" onclick="switchChecked(true)" value="选中">
<input type="button" onclick="switchChecked(false)" 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火狐下第二次无法勾选的解决方法
- JQuery 设置checkbox值二次无效的解决方法
- jQuery 更改checkbox的状态,无效的解决方法
- jquery中checkbox全选失效的解决方法
- 多个jquery.datatable共存,checkbox全选异常的快速解决方法
- JQuery触发radio或checkbox的change事件
- jQuery判断checkbox是否选中的3种方法
- JQuery对checkbox操作 (循环获取)
- jquery操作复选框(checkbox)的12个小技巧总结
- JQUERY复选框CHECKBOX全选,取消全选
- Jquery遍历checkbox获取选中项value值的方法
- jQuery操作CheckBox的方法介绍(选中,取消,取值)
- jQuery中checkbox反复调用attr(''checked'', true/false)只有第一次生效的解决方法
相关文章
jquery 重写 ajax提交并判断权限后 使用load方法报错解决方法
这篇文章主要介绍了jquery 重写 ajax提交并判断权限后 使用load方法报错解决方法 的相关资料,需要的朋友可以参考下2016-01-01
Jquery $.getJSON 在IE下的缓存问题解决方法
$.getJSON 的url都是相同的 问题来了 我修改 或者 新增树节点 然后刷新tree IE竟然毫无变化 在其他浏览器上面都OK,于是搜到一个可行的解决方法2014-10-10
jQuery.cookie.js实现记录最近浏览过的商品功能示例
这篇文章主要介绍了jQuery.cookie.js实现记录最近浏览过的商品功能,结合实例形式分析了基于jQuery.cookie.js插件创建cookie及保存浏览记录的操作技巧,需要的朋友可以参考下2017-01-01
jQuery validate 中文API 附validate.js中文api手册
jQuery validate 中文API 附validate.js中文api手册2010-07-07
jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码分享
这篇文章主要介绍了jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码,非常的简单实用,效果也很棒,有需要的小伙伴可以参考下。2015-04-04


最新评论