js实现复选框
实现复选框的基本方法
使用HTML的<input type="checkbox">元素创建复选框,并通过JavaScript监听其状态变化。
<input type="checkbox" id="myCheckbox"> 选项标签
const checkbox = document.getElementById('myCheckbox');
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log('复选框被选中');
} else {
console.log('复选框未选中');
}
});
获取复选框的状态
通过checked属性可以获取或设置复选框的选中状态。
// 获取状态
const isChecked = checkbox.checked;
// 设置状态
checkbox.checked = true; // 选中
checkbox.checked = false; // 取消选中
处理多个复选框
对于多个复选框,可以通过querySelectorAll获取所有复选框并批量处理。

<input type="checkbox" class="group-checkbox" value="option1"> 选项1
<input type="checkbox" class="group-checkbox" value="option2"> 选项2
<input type="checkbox" class="group-checkbox" value="option3"> 选项3
const checkboxes = document.querySelectorAll('.group-checkbox');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
console.log(`复选框 ${this.value} 的状态: ${this.checked}`);
});
});
全选/取消全选功能
通过一个主复选框控制多个子复选框的选中状态。
<input type="checkbox" id="selectAll"> 全选/取消全选
<input type="checkbox" class="item-checkbox" value="item1"> 项目1
<input type="checkbox" class="item-checkbox" value="item2"> 项目2
const selectAll = document.getElementById('selectAll');
const itemCheckboxes = document.querySelectorAll('.item-checkbox');
selectAll.addEventListener('change', function() {
itemCheckboxes.forEach(checkbox => {
checkbox.checked = this.checked;
});
});
动态生成复选框
通过JavaScript动态创建复选框并添加到DOM中。

const container = document.getElementById('checkbox-container');
const options = ['选项A', '选项B', '选项C'];
options.forEach(option => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = option.toLowerCase();
checkbox.value = option;
const label = document.createElement('label');
label.htmlFor = option.toLowerCase();
label.textContent = option;
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement('br'));
});
表单提交时获取选中的复选框
在表单提交时,收集所有被选中的复选框的值。
<form id="myForm">
<input type="checkbox" name="interests" value="sports"> 运动
<input type="checkbox" name="interests" value="music"> 音乐
<input type="checkbox" name="interests" value="reading"> 阅读
<button type="submit">提交</button>
</form>
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
const selected = [];
document.querySelectorAll('input[name="interests"]:checked').forEach(checkbox => {
selected.push(checkbox.value);
});
console.log('选中的选项:', selected);
});
使用事件委托优化性能
对于大量动态生成的复选框,使用事件委托可以提高性能。
document.addEventListener('change', function(e) {
if (e.target.matches('.dynamic-checkbox')) {
console.log(`复选框 ${e.target.value} 的状态变化: ${e.target.checked}`);
}
});






