首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用for循环来判断多个切换开关的真假?

如何使用for循环来判断多个切换开关的真假?
EN

Stack Overflow用户
提问于 2020-11-18 19:00:07
回答 2查看 46关注 0票数 0

https://www.w3schools.com/code/tryit.asp?filename=GKTIU8SG2RMP

代码语言:javascript
复制
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循环,因此将有许多按钮,如果解决方案是一个接一个地声明按钮,效率会很低。

EN

回答 2

Stack Overflow用户

发布于 2020-11-18 19:03:55

querySelector查找与选择器匹配的第一个元素。如果要查找多个,可以使用返回NodeList (类似于数组)的querySelectorAll。例如:

代码语言:javascript
复制
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:该代码依赖于NodeListforEach方法,该方法是在2017年左右添加的。但对于过时的环境,它很容易被多填充,我在this other SO answer中描述了如何使用它。

票数 3
EN

Stack Overflow用户

发布于 2020-11-18 19:06:28

document.querySelector从DOM返回单个(第一个)结果,而不是返回所有节点。如果需要与指定选择器匹配的所有元素的列表,则应改用document.querySelectorAll。所以在你的例子中:

代码语言:javascript
复制
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');
    }
  });
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64891735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档