用html javascript编程列出多个复选框选项,实现计算选中的总计,实现全选、反选、不选按钮功能
<!DOCTYPE html>
<html>
<head>
<title>复选框列表</title>
<script>
// 获取复选框列表
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
// 获取选中的复选框数组
const selectedCheckboxes = [];
// 初始化选中数组为空
selectedCheckboxes.length = 0;
// 响应全选按钮事件
const fullSelectionCheckbox = document.querySelector('#full-selection');
fullSelectionCheckbox.addEventListener('click', function () {
// 获取所有选中的复选框元素
const selectedCheckboxes = checkboxes.forEach(checkbox => checkbox.checked);
// 将选中的复选框数组添加到选中数组
selectedCheckboxes.forEach(checkbox => {
selectedCheckboxes.push(checkbox);
});
// 更新选中数组的总数
const total = selectedCheckboxes.length;
// 更新页面显示
document.querySelector('#total-selection').innerHTML = total;
});
// 响应反选按钮事件
const inverseSelectionCheckbox = document.querySelector('#inverse-selection');
inverseSelectionCheckbox.addEventListener('click', function () {
// 获取所有选中的复选框元素
const selectedCheckboxes = checkboxes.forEach(checkbox => checkbox.checked);
// 移除选中的复选框元素
selectedCheckboxes.forEach(checkbox => {
checkbox.checked = false;
});
// 更新选中数组的总数
const total = selectedCheckboxes.length;
// 更新页面显示
document.querySelector('#total-selection').innerHTML = total;
});
// 响应不选按钮事件
const noneSelectionCheckbox = document.querySelector('#none-selection');
noneSelectionCheckbox.addEventListener('click', function () {
// 获取所有选中的复选框元素
const selectedCheckboxes = checkboxes.forEach(checkbox => checkbox.checked);
// 移除选中的复选框元素
selectedCheckboxes.forEach(checkbox => {
checkbox.checked = false;
});
// 更新选中数组的总数
const total = checkboxes.length;
// 更新页面显示
document.querySelector('#total-selection').innerHTML = total;
});
</script>
</head>
<body>
<!-- 复选框列表 -->
<h2>复选框列表</h2>
<ul>
<li>
<input type="checkbox" id="one">
第一选项
</li>
<li>
<input type="checkbox" id="two">
第二选项
</li>
<li>
<input type="checkbox" id="three">
第三选项
</li>
<li>
<input type="checkbox" id="four">
第四选项
</li>
</ul>
<!-- 显示选中项的总计 -->
<h2>选中项的总计</h2>
<p id="total-selection"></p>
<!-- 响应全选/反选/不选按钮事件 -->
<h2>响应事件</h2>
<button id="full-selection">全选</button>
<button id="inverse-selection">反选</button>
<button id="none-selection">不选</button>
</body>
</html>