用Jquery实现一个子级复选框逐个全部选中,则全选按钮自动选中,子级按钮有一个取消则全选按钮自动取消的效果时发现有如下图所示的问题:
只有用另外的全选与全不选按钮才能变化
前面的全选与全不选按钮使用的方法也是prop()
$(function(){
var $checkbox = $("[name=items]:checkbox");//避免多次启用选择器选取
$("#selectAll").click(function(){
$checkbox.prop("checked",true);
});
$("#selectNone").click(function(){
$checkbox.prop("checked",false);
});
$("#sp").click(function(){
console.log($("#sp").attr("checked"));//undefined,如果被选中了就是checked
console.log($("#sp").prop("checked"));//true
});
$("#reverseSelect").click(function(){
$checkbox.each(function(){
$(this).prop("checked",!$(this).prop("checked"));
console.log($(this).prop("checked"));//true
})
});
$("#test").click(function(event){
var str = "";
$("[name=items]:checkbox:checked").each(function(){
str += $(this).val() + "\r\n";
});
console.log(str);
event.preventDefault();
});
$("#all_none").click(function(){//puzzle 若将data-xxx设置为"true",则判断条件需为true(无引号)
if($(this).data("click") == "selectAll"){
$checkbox.prop("checked",true);
$(this).data("click","selectNone");
}else{
$checkbox.prop("checked",false);
$(this).data("click","selectAll");
}
console.log($(this).data("click"));
});
//#all-none-checkbox为需要联动的那个全选框
$("#all_none_checkbox").click(function(){
$checkbox.prop("checked",$(this).prop("checked"));
});
$("[name=items]:checkbox").click(function(){
var flag = true;
$("[name=items]:checkbox").each(function(){
if(!$(this).prop("checked")){
flag = false;
}else{
flag = true;
}
});
console.log($(this).prop("checked"));
console.log(flag);
$("#all_none_checkbox").prop("checked",flag);
});
})
已经在百度上走了一遭,查到的大部分方法同样无法奏效...还请大佬赐教
你的flag计算出来后都没做判断要不要勾选全选