https://www.w3schools.com/code/tryit.asp?filename=GKTIU8SG2RMP
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
// do this
console.log('Checked');
} else {
// do that
console.log('Not checked');
}
});
});在链接上面,当第一个按钮被点击时,我完美地得到了它的状态(选中或未选中)。但是,对于第二个按钮,它不显示状态(选中或未选中)。我该如何解决这个问题?非常感谢您的关注。注意:我为按钮使用了for循环,因此将有许多按钮,如果解决方案是一个接一个地声明按钮,效率会很低。
发布于 2020-11-18 19:03:55
querySelector查找与选择器匹配的第一个元素。如果要查找多个,可以使用返回NodeList (类似于数组)的querySelectorAll。例如:
function checkboxChangeHandler() {
if (this.checked) { // <== Note use of `this`
// do this
console.log('Checked');
} else {
// do that
console.log('Not checked');
}
}
document.addEventListener('DOMContentLoaded', function () {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', checkboxChangeHandler);
});
});注意:该代码是用ES5编写的,因为您的原始代码是这样写的,但通常我会使用const和迭代性等ES2015+特性。
注2:该代码依赖于NodeList的forEach方法,该方法是在2017年左右添加的。但对于过时的环境,它很容易被多填充,我在this other SO answer中描述了如何使用它。
发布于 2020-11-18 19:06:28
document.querySelector从DOM返回单个(第一个)结果,而不是返回所有节点。如果需要与指定选择器匹配的所有元素的列表,则应改用document.querySelectorAll。所以在你的例子中:
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
// do this
console.log('Checked');
} else {
// do that
console.log('Not checked');
}
});
});https://stackoverflow.com/questions/64891735
复制相似问题