jquery操作checkbox火狐下第二次无法勾选的解决方法

2020-05-24 21:24:22易采站长站整理

最近在学习jQuery(版本jquery-1.9.1.js),要求用jQuery实现全选/全不选、反选,在IE(IE8)中没有问题,但在火狐浏览器中调试的时候出现了一些小问题,达不到效果。

html代码如下:


<div>
你爱好的运动是
<input type="checkbox" id="selectal1" /><label for="selectal1">全选/全不选</label><br/>

<input name="intrest" type="checkbox" />足球
<input name="intrest" type="checkbox" />篮球
<input name="intrest" type="checkbox" />羽毛球
<input name="intrest" type="checkbox" />乒乓球<br/>
<button id="allbtn">全选</button>
<button id="notallbtn">全不选</button>
<button id="reversebtn">反选</button>
<button>提交</button>
</div>

jQuery代码:


<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
$().ready(function(){
//全选/全不选复选框
$("#selectal1").click( function(){
if($(this).attr("checked")==true){
$("input:checkbox[id!='selectal1']").each(function() {
$(this).attr("checked",true);
});
}else{
$("input:checkbox[id!='selectal1']").each(function() {
$(this).attr("checked",false);
});
}
});
//全选按钮
$("#allbtn").click(function(){
$("input:checkbox[id!='selectal1']").each(function() {
$(this).attr("checked",true);
});
});
//全不选按钮
$("#notallbtn").click(function(){
$("input:checkbox[id!='selectal1']").each(function() {
$(this).attr("checked",false);
});
});
//反选按钮
$("#reversebtn").click(function(){
$("input:checkbox[id!='selectal1']").each(function() {
$(this).attr("checked",!$(this).attr("checked"));
});
});
})
</script>

复选框绑定了click事件,点一次选中,再点击取消选中,依次类推。这个功能在IE8中没问题,但是在firefox中测试的时候,前两次都没有问题,可以正常显示选中和取消,但当再去选中的时候,复选框的属性checkbox值变为”checked”,没问题,但是复选框却不在显示选中状态,明明属性值改了,但是却不显示勾选,我以为是浏览器缓存的问题,但是删除缓存还是不行……..后来在网上看到了方法,说是jQuery版本的问题,jQuery1.6以上用attr会存在兼容性问题,得换成prop。

查了下API prop属性是这样的:

prop(name|properties|key,value|fn)

概述