js实现全选和反选
实现全选功能
通过获取所有复选框元素,并设置它们的checked属性为true来实现全选。使用querySelectorAll选择所有目标复选框。
function selectAll() {
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = true;
});
}
实现反选功能
遍历所有复选框,将它们的checked属性取反。通过逻辑非操作符!实现状态切换。

function invertSelection() {
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = !checkbox.checked;
});
}
动态绑定事件
为全选和反选按钮添加事件监听器,确保点击时触发对应函数。通过addEventListener实现交互绑定。
document.getElementById('selectAllBtn').addEventListener('click', selectAll);
document.getElementById('invertBtn').addEventListener('click', invertSelection);
示例HTML结构
创建包含复选框和操作按钮的基础HTML结构。复选框需统一类名或特征以便选择器定位。

<input type="checkbox" class="item-checkbox"> 选项1
<input type="checkbox" class="item-checkbox"> 选项2
<input type="checkbox" class="item-checkbox"> 选项3
<button id="selectAllBtn">全选</button>
<button id="invertBtn">反选</button>
限定范围的全选/反选
若需针对特定容器内的复选框,可通过父元素限定选择范围。使用更精确的选择器提高代码针对性。
function selectAllInContainer() {
const container = document.getElementById('checkboxContainer');
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = true;
});
}
性能优化建议
对于大量复选框操作,建议使用事件委托或减少DOM操作次数。通过文档片段或批量更新提升执行效率。
function batchUpdateCheckboxes(shouldCheck) {
const fragment = document.createDocumentFragment();
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
const clone = checkbox.cloneNode(true);
clone.checked = shouldCheck;
fragment.appendChild(clone);
});
checkboxContainer.innerHTML = '';
checkboxContainer.appendChild(fragment);
}






