<!--
if all checkboxes are not 'checkecd' then check all
if some are 'checked' then check all
if all are 'checked' then uncheck all
-->
const btn = document.querySelector('button');
btn.addEventListener('click',()=>{
const allboxes = document.querySelectorAll('input[type="checkbox"]');
allboxes.forEach(box => {
if(!box.checked){
box.checked = true;
} else {
box.checked = false;
}
})
})
<button>select all</button>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
您可以使用数组some
和every
。用some
检查是否已选中某些元素,并用every
检查是否已全部选中。然后相应地选中或取消选中
const btn = document.querySelector('button');
btn.addEventListener('click', () => {
const allboxes = document.querySelectorAll('input[type="checkbox"]');
// if some of the checkbox is checked
const isSomeCheck = [...allboxes].some(item => item.checked);
// if all are checked
const isAllChecked = [...allboxes].every(item => item.checked);
// if some are checked then on click of button check all
if (isSomeCheck) {
allboxes.forEach(item => item.checked = true)
}
// if all are checked then uncheck all
if (isAllChecked && isSomeCheck) {
allboxes.forEach(item => item.checked = false)
}
})
<button>select all</button>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
具有CSS伪类querySelectorAll
的[好旧:checked
,可以抢救。您可以通过将length
比较移到forEach
中来进一步缩短此时间。
/*
if all checkboxes are not 'checkecd'
then check all
if some are 'checked'
then check all
if all are 'checked'
then uncheck all
*/
const btn = document.querySelector('button');
btn.addEventListener('click', () => {
const allboxes = document.querySelectorAll('input[type="checkbox"]');
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');
const allChecked = allboxes.length === checkedBoxes.length;
allboxes.forEach(box => box.checked = !allChecked);
})
<button>select all</button>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
您可以使用Array.prototype.every()
和Array.prototype.every()
。例如这样:
Array.prototype.some()