先来说一下今天遇到的需求,首先有多个多选框,需要实现全选功能,我是按钮的方式控制是否全选,如下图所示:
当我点击全选时,下面的checkbox会全选上,下面是我的页面层级结构:
<label class="cont_list_item">
<div class="cont_list_checkbox">
<input class="item_check" type="checkbox" />
<i class="item_check_icon"></i>
</div>
</label>
原先是用的这种:
$(obj).on("click",function(e){
$("cont_list_item .item_check").each(function(){
if($(this).attr("checked")){
$(this).attr("checked","checked");
}else{
$(this).removeAttr("checked");
}
});
});
其实逻辑上,上面的代码是没得毛病的,但是你这么操作:
你先使用全选按钮让他们都全选上,然后再手动地去把其中一个取消选择,这时你会发现你的全选按钮控制不住他了,但是其他checkbox还是能正常控制;感觉就很无语后来还是找到了解决的办法了的。
js解决办法(完整代码版,使用jq.prop()替换jq.attr()):
$("#AllCheck").on("click",function(e){
var that = $(this);
var IsChecked = $(this).attr("data_check");
if(IsChecked == "" || IsChecked == "false"){//全选
that.html("全不选");
that.attr("data_check","true");
$(".cont_list .item_check").each(function(){
if($(this).is(':checked')){
console.log("xuan");
}else{
$(this).prop("checked",true);
console.log("meix");
}
});
}else{//取消全选
that.html("全选");
that.attr("data_check","false");
$(".cont_list .item_check").each(function(){
if($(this).is(':checked')){
$(this).prop("checked",false);
}
});
}