【问题标题】:Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLImageElement.<anonymous>未捕获的类型错误:无法读取 HTMLImageElement 处未定义的属性“切换”。<匿名>
【发布时间】:2020-11-26 08:23:56
【问题描述】:

代码如下:

let imagenes = document.querySelectorAll(".team");
let modal = document.querySelectorAll("#modal");
let img = document.querySelectorAll("#modal__img");
let boton = document.querySelectorAll("#modal__boton");

for (let i = 0; i < imagenes.length; i++){
  imagenes[i].addEventListener("click", function(e){
    modal.classList.togle("modal--open");
  })
}

错误:

Uncaught TypeError: Cannot read property 'toggle' of undefined    at HTMLImageElement.<anonymous>"

【问题讨论】:

  • 我怀疑这个 sn-p 代码没有正确反映错误,因为 togletoggle 不同。因此,请确保从代码中复制并粘贴准确的 sn-p。

标签: javascript dom


【解决方案1】:

document.querySelectorAll 返回具有类似数组数据结构的NodeList。因此,modal 是一个没有 classList 属性的数组。使用document.getElementById;反正更快:

let modal = document.getElementById("#modal");

【讨论】:

    【解决方案2】:

    如果您使用querySelectorAll,您将获得一个HTML 集合,因此您需要遍历它的元素来切换一个类。如果您只想切换一个元素,则定位速度更快,但如果您需要切换多个元素,您的代码将如下所示

    const elements = document.quesySelectorAll('.myClass');
    elements.forEach(x => x.classList.toggle('otherClass');
    

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 2016-08-08
      • 2021-11-03
      • 2018-03-10
      • 2014-06-09
      • 2021-12-22
      • 1970-01-01
      • 2015-01-06
      相关资源
      最近更新 更多