<body>
<p>请选择你的爱好:
<label>
<input type="checkbox" id="allNotAll">全选/全不选
</label>
</p>
<label>
<input type="checkbox" name="allInput">踢足球
</label>
<label>
<input type="checkbox" name="allInput">上网
</label>
<label>
<input type="checkbox" name="allInput">写代码
</label>
<label>
<input type="checkbox" name="allInput">写文档
</label>
<label>
<input type="checkbox" name="allInput">查BUG
</label>
<div>
<button id="allChange">全选</button>
<button id="allCloseChange">全不选</button>
<button id="overChange">反选</button>
</div>
<script>
let allInput = document.getElementsByName('allInput');
var checkbox = document.getElementById('allNotAll');
// 全选封装
function getAllChange() {
let allChange = document.querySelector('#allChange');
for (let i = 0; i < allInput.length; i++) {
allInput[i].checked = true;
}
}
// 全不选封装
function closeAllChange() {
let allCloseChange = document.querySelector('#allCloseChange');
for (let i = 0; i < allInput.length; i++) {
allInput[i].checked = false;
}
}
// 全选
allChange.addEventListener('click', getAllChange)
// 全不选
allCloseChange.addEventListener('click', closeAllChange)
// 反选
overChange.addEventListener('click', () => {
let overChange = document.querySelector('#overChange');
for (let i = 0; i < allInput.length; i++) {
allInput[i].checked = !allInput[i].checked
}
})
allNotAll.addEventListener('change',function(){
if(this.checked){
getAllChange()
}else{
closeAllChange()
}
})
</script>
</body>