如果某些复选框为';选中';然后检查所有javascript

如果某些复选框为';选中';然后检查所有javascript,javascript,input,checkbox,checkboxlist,Javascript,Input,Checkbox,Checkboxlist,const btn=document.querySelector('button'); btn.addEventListener('单击',()=>{ const allboxes=document.querySelectorAll('input[type=“checkbox”]”); allbox.forEach(box=>{ 如果(!box.checked){ box.checked=true; }否则{ box.checked=false; } }) }) 全选 您可以使用数组一些和每个。


const btn=document.querySelector('button');
btn.addEventListener('单击',()=>{
const allboxes=document.querySelectorAll('input[type=“checkbox”]”);
allbox.forEach(box=>{
如果(!box.checked){
box.checked=true;
}否则{
box.checked=false;
}
})
})
全选

您可以使用数组
一些
每个
。使用
some
检查是否选中了部分元素,使用
every
检查是否选中了所有元素。然后相应地勾选或取消勾选

const btn=document.querySelector('button');
btn.addEventListener('单击',()=>{
const allboxes=document.querySelectorAll('input[type=“checkbox”]”);
//如果选中了某些复选框
常量isSomeCheck=[…所有框].some(项=>item.checked);
//如果全部检查完毕
常量isAllChecked=[…所有框].every(项=>item.checked);
//如果选中了一些,则单击按钮“全部选中”
如果(isSomeCheck){
allbox.forEach(item=>item.checked=true)
}
//如果选中全部,则取消选中全部
如果(isAllChecked&&isSomeCheck){
allbox.forEach(item=>item.checked=false)
}
})
全选
您可以使用和。 例如:

if(Array.prototype.every.call(allbox,box=>!box.checked)){
forEach(box=>box.checked=true);
}else if(Array.prototype.every.call(allbox,box=>box.checked)){
allbox.forEach(box=>box.checked=false);
}else if(Array.prototype.some.call(allbox,box=>box.checked)){
forEach(box=>box.checked=true);
}

Good old
queryselectoral
with CSS pseudo class
:选中以营救。通过将
length
比较移动到
forEach
中,您可以进一步缩短此时间

/*
如果所有复选框都不是“checkecd”
然后全部检查
如果一些被“检查”
然后全部检查
如果全部“检查”
然后取消选中全部
*/
const btn=document.querySelector('button');
btn.addEventListener('单击',()=>{
const allboxes=document.querySelectorAll('input[type=“checkbox”]”);
const checkedboxs=document.querySelectorAll('input[type=“checkbox”]:checked');
const allChecked=allbox.length==checkedboxs.length;
forEach(box=>box.checked=!allChecked);
})
全选

这两个复选框的意思相同
如果所有复选框都不是“checkecd”,那么选中所有复选框如果部分复选框是“选中”的,那么选中所有复选框;如果所有复选框都是“未选中”的,那么选中所有复选框;如果部分复选框是“已选中”的,那么选中所有复选框;如果部分复选框是“已选中”的,那么选中所有复选框;这是否回答了您的问题?你需要检查的就是是否所有的都检查过了;如果是,则全部取消选中。否则,请全部检查。