5 页面中有5个复选框,1个按钮,点击按钮的时候打印选中的复选框数目
时间: 2024-02-22 08:58:15 浏览: 54
可以使用以下代码实现:
```html
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
<input type="checkbox" id="checkbox3">
<input type="checkbox" id="checkbox4">
<input type="checkbox" id="checkbox5">
<button onclick="countChecked()">打印选中的复选框数目</button>
<script>
function countChecked() {
const checkboxes = document.querySelectorAll("input[type='checkbox']");
let count = 0;
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
count++;
}
}
console.log(`选中了 ${count} 个复选框。`);
}
</script>
```
在这个代码中,我们首先定义了 5 个复选框和 1 个按钮。当按钮被点击时,会调用 countChecked 函数。在这个函数中,我们使用 querySelectorAll 函数获取所有类型为 checkbox 的输入元素,然后遍历这些元素,统计选中的复选框数目。最后,使用 console.log 函数打印选中的复选框数目。
阅读全文
相关推荐
















