[英]"Cannot read property addEventListener of null" when adding EventListener JavaScript
I am trying to add an eventListener to a variable set to an element.我正在尝试将 eventListener 添加到设置为元素的变量中。 The code is this:代码是这样的:
var c = document.getElementById("some_element");
c.addEventListener("click", someFunction);
(BTW if it helps the element is a button .) (顺便说一句,如果它有助于元素是一个按钮。)
It seems this code is getting execute before the dom is ready & at that point the element is available in DOM so it is throwing null
似乎这段代码在 dom 准备好之前正在执行 & 那时元素在 DOM 中可用所以它抛出null
Try by adding the code neae closing end of body tag尝试通过添加代码 neae 结束 body 标签结束
<body>
// rest of html elmeent
<script>
var c = document.getElementById("some_element");
c.addEventListener("click", someFunction);
</script>
</body>
Also you can put your code inside window.onload你也可以把你的代码放在window.onload里面
window.onload = function(){
var c = document.getElementById("some_element");
c.addEventListener("click", someFunction);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.