繁体   English   中英

如何解决:“未捕获的TypeError:无法读取null的属性'addEventListener'”…?

[英]how to fix it: “Uncaught TypeError: Cannot read property 'addEventListener' of null”…?

我从视频教程中学习html / css / js。 我正在学习如何编写js代码,但我无助于解决问题。 希望您能给我解决方案的人。 问题是关于add.EventListener的。 当我在chrome中运行代码时,在控制台中显示:“ app.js:11 Uncaught TypeError:无法读取null的'addEventListener'属性”,希望在您的帮助下解决此问题。 谢谢!

const computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreBoard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const p_div = document.getElementById("p");
const r_div = document.getElementById("r");
const s_div = document.getElementById("s");

p_div.addEventListener('click', function() {
    console.log("hey you clicked on p");
})`

当页面上没有具有该ID的元素时, document.getElementById('p')将返回null。 我建议您浏览HTML并确保您实际上具有带有该ID的元素。

您可以console.log(p_div)创建之后不断地看到元素的值尝试之前addEventListener

您可以检查p_div是否存在。

if(p_div) {
  p_div.addEventListener('click', function() {
    console.log("Hey you clicked on p");
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM