使用 JavaScript 动态生成复选框,并将它们添加到页面中,并实现全选及取消
使用 JavaScript 动态生成复选框,并将它们添加到页面中,并实现全选及取消<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态生成复选框示例</title>
<style>
/* 样式设置 */
.checkbox-label {
display: flex;
align-items: center; /* 垂直居中对齐 */
margin-bottom: 4px; /* 每个复选框之间的间距,已减小 */
}
.checkbox-label input {
margin-right: 8px; /* 复选框与文本之间的间距 */
}
</style>
<script>
// 初始化复选框选项
const options = ['选项1', '选项2', '选项3', '选项4'];
function toggleCheckboxes(source) {
const checkboxes = document.querySelectorAll('.checkbox');
checkboxes.forEach(checkbox => {
checkbox.checked = source.checked;
});
}
function updateSelectAllCheckbox() {
const checkboxes = document.querySelectorAll('.checkbox');
const selectAllCheckbox = document.getElementById('selectAll');
selectAllCheckbox.checked = Array.from(checkboxes).every(checkbox => checkbox.checked);
}
// 动态生成复选框
function createCheckboxes() {
const container = document.getElementById('checkboxContainer');
options.forEach(option => {
const label = document.createElement('label');
label.className = 'checkbox-label'; // 添加类名以应用样式
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'checkbox';
checkbox.onclick = updateSelectAllCheckbox; // 添加点击事件
label.appendChild(checkbox);
label.appendChild(document.createTextNode(option));
container.appendChild(label);
});
}
// 在页面加载时创建复选框
window.onload = function() {
createCheckboxes();
};
</script>
</head>
<body>
<h1>动态生成复选框示例</h1>
<label>
<input type="checkbox" id="selectAll" onclick="toggleCheckboxes(this)"> 全选
</label>
<br>
<div id="checkboxContainer"></div> <!-- 动态生成复选框的容器 -->
</body>
</html>
页:
[1]