html页面如下:
* 全选:
(“#checkAll”).click(function(event){
console.log(event.target);
$(“input[name=’items’]”).attr(“checked”,true);
});
在项目中遇到过这种情况:使用以上代码实现全选功能,第一次的时候可以实现全选功能,但是后面就失效了我用火狐浏览器调试了一下,操作的复选框已经有了check属性但是页面并未显示出来。然后上网查了一下是因为对于不同版本的jQuery,attr()和prop()是有细小的区别的。jQuery1.6之前的版本attr()在取某些值时返回的是property的值,这样就造成了返回结果不一致。从jQuery1.6开始prop()方法返回property的值而attr()方法返回atributes的值。
因此我们最好使用:(“#checkAll”).click(function(){
$(“input[name=items]”).prop(“checked”,true);
});
* 全不选:
(“#checkNo”).click(function(){(“input[name=’items’]”).prop(“checked”,false);
//或者使用$(“input[name=’items’]”).attr(“checked”,false);
});
* 反选:(反选说的就是如果你选中了,那么我就要给你没选中。如果你没选中,我就要选中。)
那么我们肯定就要遍历复选框去检验那个复选框是不是选中状态然后再更改其状态。
(“#checkRev”).click(function(){(“input[name=’items’]”).each(function(){
this.checked = ! this.checked;
});
});
如果不用按钮来控制全选等操作,而是用复选框,那效果又不一样了,如下所示:
(“#checkAll”).click(function(){
if(this.checked){(“input[name=’items’]”).prop(“checked”,true);
}else{
$(“input[name=’items’]”).attr(“checked”,false);
}
});
当然我们可以简化为:
* 还有一种需求就是说当我们全部选中之后,所有选项都处于选中状态,而我们现在只是取消某一个复选框的选中状态,那么需要我们的全选按钮也应该处于不选中状态。
思路:首先要给复选框组绑定一个事件,此事件中定义一个变量flag为true,检查复选框组中是否有不处于选中状态的时候,就让flag设置为false,此时我们根据flag的值来判断是否需要将复选框的选中状态。
(“input[name=’items’]”).click(function(){
var flag = true;(“input[name=’items’]”).each(function(){
if(!this.checked){
flag = false;
}
});
console.log(flag);
$(“#checkAll”).prop(“checked”,flag);
});