Javascript 无法读取 null 的属性“addEventListener”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26107125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:21:37  来源:igfitidea点击:

Cannot read property 'addEventListener' of null

javascriptfunctiongetelementbyidaddeventlistener

提问by morocklo

I have to use vanilla JavaScript for a project. I have a few functions, one of which is a button that opens a menu. It works on pages where the target id exists, but causes an error on pages where the id doesn't exist. On those pages where the function cannot find the id, I receive a "Cannot read property 'addEventListener' of null " error and none of my other functions work.

我必须在一个项目中使用 vanilla JavaScript。我有几个功能,其中之一是打开菜单的按钮。它适用于目标 id 存在的页面,但在 id 不存在的页面上会导致错误。在函数找不到 id 的那些页面上,我收到“无法读取 null 属性 'addEventListener'”错误,并且我的其他函数都不起作用。

Below is the code for the button that opens the menu.

下面是打开菜单的按钮的代码。

function swapper() {
toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
el.addEventListener('click', swapper, false);

var text = document.getElementById('overlayBtn');
text.onclick = function(){
this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
return false;
};

How do I deal with this? I probably need to all wrap this code in another function or use an if/else statement so that it only searches for the id on specific pages, but not sure exactly.

我该如何处理?我可能需要将此代码全部包装在另一个函数中或使用 if/else 语句,以便它仅搜索特定页面上的 id,但不确定是否准确。

回答by Rob M.

I think the easiest approach would be to just check that elis not null before adding an event listener:

我认为最简单的方法el是在添加事件侦听器之前检查它是否为空:

var el = document.getElementById('overlayBtn');
if(el){
  el.addEventListener('click', swapper, false);
}

回答by Dilip Agheda

It seems that document.getElementById('overlayBtn');is returning nullbecause it executes before the DOM fully loads.

似乎document.getElementById('overlayBtn');正在返回,null因为它在 DOM 完全加载之前执行。

If you put this line of code under

如果你把这行代码放在

window.onload=function(){
  -- put your code here
}

then it will run without issue.

那么它将毫无问题地运行。

Example:

例子:

window.onload=function(){
    var mb = document.getElementById("b");
    mb.addEventListener("click", handler);
    mb.addEventListener("click", handler2);
}


function handler() {
    $("p").html("<br>" + $("p").text() + "<br>You clicked me-1!<br>");
}

function handler2() {
    $("p").html("<br>" + $("p").text() + "<br>You clicked me-2!<br>");
}

回答by sridhar

I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.

我遇到了类似的情况。这可能是因为脚本是在页面加载之前执行的。通过将脚本放在页面底部,我避开了这个问题。

回答by MattSidor

I was getting the same error, but performing a null check did not seem to help.

我遇到了同样的错误,但执行空检查似乎没有帮助。

The solution I found was to wrap my function inside an event listener for the whole document to check when the DOM finished loading.

我找到的解决方案是将我的函数包装在整个文档的事件侦听器中,以检查 DOM 何时完成加载。

document.addEventListener('DOMContentLoaded', function () {
    el.addEventListener('click', swapper, false);
});

I think this is because I am using a framework (Angular) that is changing my HTML classes and ID's dynamically.

我认为这是因为我使用的框架 (Angular) 正在动态更改我的 HTML 类和 ID。

回答by Ajit Kumar

It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded.

只是因为你的 JS 在 HTML 部分之前被加载,所以它找不到那个元素。只需将整个 JS 代码放在一个函数中,该函数将在窗口加载时调用。

You can also put your Javascript code below the html.

您还可以将 Javascript 代码放在 html 下方。

回答by Sagar M

script is loading before body, keep script after content

脚本在正文之前加载,在内容之后保留脚本

回答by morocklo

Thanks to @Rob M. for his help. This is what the final block of code looked like:

感谢@Rob M. 的帮助。这是最后的代码块的样子:

function swapper() {
  toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
if (el){
  el.addEventListener('click', swapper, false);

  var text = document.getElementById('overlayBtn');
  text.onclick = function(){
    this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
    return false;
  };
}

回答by Andy Smith

I simply added 'async' to my script tag, which seems to have fixed the issue. I'm not sure why, if someone can explain, but it worked for me. My guess is that the page isn't waiting for the script to load, so the page loads at the same time as the JavaScript.

我只是在我的脚本标签中添加了“async”,这似乎解决了这个问题。我不知道为什么,如果有人可以解释,但它对我有用。我的猜测是页面不会等待脚本加载,因此页面与 JavaScript 加载同时加载。

Async/Await enables us to write asynchronous code in a synchronous fashion. it's just syntactic sugar using generators and yield statements to “pause” execution, giving us the ability to assign it to a variable!

Async/Await 使我们能够以同步方式编写异步代码。它只是使用生成器和 yield 语句来“暂停”执行的语法糖,使我们能够将其分配给变量!

Here's reference link- https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da

这是参考链接 - https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da

回答by matak8s

Put script at the end of body tag.

将脚本放在 body 标签的末尾。

<html>
    <body>
        .........
        <script src="main.js"></script>
    </body>
</html>

回答by ultrageek

I had the same problem, but my id was present. So I tried adding "window.onload = init;" Then I wrapped my original JS code with an init function (call it what you want). This worked, so at least in my case, I was adding an event listener before my document loaded. This could be what you are experiencing as well.

我遇到了同样的问题,但我的 ID 存在。所以我尝试添加“window.onload = init;” 然后我用一个 init 函数包装了我原来的 JS 代码(随便你怎么称呼它)。这有效,所以至少在我的情况下,我在加载文档之前添加了一个事件侦听器。这也可能是您正在经历的。