<div>
全选:<input type="checkbox" id="all" />
<div id="child">
子元素01:<input type="checkbox" /><br />
子元素02:<input type="checkbox" /><br />
子元素03:<input type="checkbox" /><br />
</div>
</div>
const all = document.getElementById('all');
const child = document.getElementById('child');
const childinput = child.getElementsByTagName('input');//子元素的个数
const arr = [],arr1=[];
all.addEventListener("change",function(){//全选 全不选
arr.splice(0,arr.length);//防止重复数组清空
if(this.checked){
for(let i=0;i<childinput.length;i++){
arr.push(i);
childinput[i].checked=true
}
}else{
for(let i=0;i<childinput.length;i++){
arr.pop(i);
childinput[i].checked=false
}
}
console.log(arr)
})
for(let i=0;i<childinput.length;i++){
childinput[i].setAttribute("key",i);
arr1.push(Number(childinput[i].getAttribute("key")));
childinput[i].addEventListener("change",function(){
const keys = Number(this.getAttribute("key"));
if(this.checked){
arr.push(keys);
if(arr.length==arr1.length){
all.checked=true
}else{
all.checked=false
}
}else{
arr.pop(keys)
all.checked=false
}
})
}