[英]I get the "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')" error in a basic JS button
I'm trying to make a button that prints the string "Button clicked" on the console when clicked, but I keep getting the error Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at course.js:70
.我正在尝试制作一个按钮,单击时在控制台上打印字符串“Button clicked”,但我不断收到错误Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at course.js:70
。
This is the code for the HTML button:这是 HTML 按钮的代码:
<button id="go-button">Go</button>
<br>
Click that button
And this the Javascript for it:这是 Javascript :
function buttonClicked(){
console.log("Button clicked");
}
var btn = document.getElementById("go-button");
btn.addEventListener("click", buttonClicked, true);
I'm following a video course from 2017 and copied the exact code the instructor wrote, but his runs as intended.我正在关注 2017 年的视频课程,并复制了讲师编写的确切代码,但他的运行符合预期。 I thought that maybe it was an outdated method and that was causing the problem, but then looked it up and about three websites showed similar examples.我认为这可能是一种过时的方法,导致了问题,但后来查了一下,大约三个网站显示了类似的例子。 Honestly, I got confused.老实说,我很困惑。
Your code seems to be executed even before the DOM getting loaded into the browser.您的代码似乎甚至在 DOM 加载到浏览器之前就已执行。
Put it under window.onload
.把它放在window.onload
下。 That way it would be able to find go-button
and then would be able to add event listener to it.这样它就能够找到go-button
,然后能够向它添加事件侦听器。
function buttonClicked(){
console.log("Button clicked");
}
window.onload=function(){
var btn = document.getElementById("go-button");
btn.addEventListener("click", buttonClicked, true);
}
Reference: Cannot read property 'addEventListener' of null参考:无法读取 null 的属性“addEventListener”
OR或者
Put your script import at the end of your HTML
's body
将脚本导入放在HTML
body
的末尾
<html>
<body>
.........
<script src="main.js"></script>
</body>
</html>
Reference: Another answer to the above question参考:上述问题的另一个答案
Add the defer attribute to the script element that links your js code in your html.将 defer 属性添加到链接 html 中的 js 代码的脚本元素。 This would prevent your code from executing before the DOM gets loaded into the browser这将阻止您的代码在 DOM 加载到浏览器之前执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.