当手动选中/取消选中任何目标复选框时,以编程方式检查所有复选框无法正常工作 我有两种方法,一种方法是选中所有复选框,另一种方法是取消选中所有复选框值
我将它们命名为 selectAll 和 unSelectall。当触发 selectAll 时,它将选中所有复选框,但是当触发 unSelectall 时,它将取消选中所有复选框,但是当您选中/取消选中任何目标复选框,然后单击全选或取消全选时,问题是什么,手动选中/未选中的复选框不起作用。这是 fiddle 上的工作代码
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while(i < checkboxes.length) {
checkboxes[i].setAttribute("checked", "checked");
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while(i < checkboxes.length) {
checkboxes[i].removeAttribute("checked", "");
i++;
}
}
最佳答案
使用直接的checked
属性,而不是setAttribute
和removeAttribute
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = true;
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = false;
i++;
}
}
演示
<!DOCTYPE html>
<html>
<body>
All:
<input onclick="selectAll();" type="checkbox" id="all"> uncheckAll:
<input onclick="unSelectAll();" type="checkbox" id="all">
<br/> ckbx1:
<input type="checkbox" class="myCheck"> ckbx2:
<input type="checkbox" class="myCheck"> ckbx3:
<input type="checkbox" class="myCheck"> ckbx4:
<input type="checkbox" class="myCheck">
<p>checl all and uncheck all</p>
<script>
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = true;
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = false;
i++;
}
}
</script>
</body>
</html>
关于javascript - 当手动选中/取消选中任何目标复选框时,以编程方式检查所有复选框无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335471/