jquery checkbox无法用attr()二次勾选问题的解决方法
今晨,漂亮的测试妹妹提了个奇怪的bug,说我一功能checkbox时隐时现,比如第一次打开有勾选,第n次打开可能就不选了。
想到与美女有亲密接触机会,马上鸡动起来。
经过偶层层抽次剥茧(dadajiangyou),终于知道了原因:attr()在二次选中勾选框时,失效。
比如,如下HTML页面,一点【选中】、二点【取消选中】、三点【选中】,瞧,不行了呗。
1.html
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>propdemo</title>
<style>
img{
padding:10px;
}
div{
color:red;
font-size:24px;
}
</style>
<scriptsrc="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<inputtype="checkbox"checked="checked">
<inputtype="checkbox">
<inputtype="checkbox">
<inputtype="checkbox"checked="checked">
<script>
$("input[type='checkbox']").prop("checked",function(i,val){
return!val;
});
</script>
</body>
</html>
解决方案,是使用prop()替换attr()方法(在Jquery1.6以上),如下代码:
2.html
<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>Attrchecked</title>
<scripttype="text/javascript"src="./js/jquery-1.11.2.js"></script>
<scripttype="text/javascript">
functionswitchChecked(flag){
$("input[type='checkbox']").prop('checked',flag);
}
</script>
</head>
<body>
<inputtype="checkbox"/>
<inputtype="button"onclick="switchChecked(true)"value="选中">
<inputtype="button"onclick="switchChecked(false)"value="取消选中">
</body>
</html>
关于官方文档,见:http://api.jquery.com/attr/
或者http://api.jquery.com/prop/
摘抄如下:“AsofjQuery1.6,the.attr()methodreturnsundefinedforattributesthathavenotbeenset.ToretrieveandchangeDOMpropertiessuchasthechecked,selected,ordisabledstateofformelements,usethe.prop()method.”
以上这篇jquerycheckbox无法用attr()二次勾选问题的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。