[英]Javascript Cannot read property 'addEventListener' of null errors
I have the problem that when executing a script the error message appears:我的问题是执行脚本时出现错误消息:
Cannot read property 'addEventListener' of null
无法读取 null 的属性“addEventListener”
My JavaScript code:我的 JavaScript 代码:
var bghtooltipin = document.getElementById('bgh-tooltipin1');
var bghtooltipout = document.getElementById('bgh-tooltipout1');
bghtooltipin.addEventListener('mouseover', mouseOver);
bghtooltipin.addEventListener('mouseout', mouseOut);
I looked at a lot of troubleshooting tips but didn't find anything that would fix my problem.我查看了很多故障排除提示,但没有找到任何可以解决我的问题的方法。
Cannot read property addEventListener of null
would happen when you're trying to access that property of null.当您尝试访问 null 的属性时,会发生
Cannot read property addEventListener of null
情况。 The error just means that, if you're doing this:错误只是意味着,如果你这样做:
myElement.addEventListener("click", function () {
//some code
});
then myElement
isn't defined like you think it is.那么
myElement
并没有像您想象的那样定义。 Without any code, I can't help anymore, but my best advice is to go to where you define myElement
.没有任何代码,我无法再提供帮助,但我最好的建议是 go 到您定义
myElement
的位置。 Likely, that line has something wrong with it.很可能,那条线有问题。
You have to write your javascript at the end of body or initialize it with DOMContentLoaded.您必须在正文的末尾编写 javascript 或使用 DOMContentLoaded 对其进行初始化。 The problem is your, document is not complete at the time, when you try to select your element.
问题是你的,当时文件不完整,当你尝试 select 你的元素时。
<script> document.addEventListener('DOMContentLoaded', function() { document.querySelector('#elem').addEventListener('click', function() { this.innerText += ';'; }); }); </script> <button id="elem">Click me</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.