Javascript:为什么我会收到此未捕获的类型错误:无法读取 null 的属性“addEventListener”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31274282/
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-10-28 13:34:21  来源:igfitidea点击:

Javascript: Why am I getting this Uncaught TypeError: Cannot read property 'addEventListener' of null?

javascriptgoogle-chrome

提问by the_velour_fog

I am trying to register an event handler that appends an element into the DOM when a button fires a click event,e.g.

我正在尝试注册一个事件处理程序,当按钮触发点击事件时,该事件处理程序将一个元素附加到 DOM 中,例如

var b = document.getElementById('evt');

var eventDemo = function(event) {

    console.log('I handled the event');
    console.log(event);
    console.log(Object.prototype.toString.call(event)); 

var imgElement = document.createElement('img');
imgElement.src = 'http://lorempixel.com/150/150/';
document.body.appendChild(imgElement);

};

b.addEventListener('onclick', eventDemo, false);

but I keep getting:

但我不断得到:

Uncaught TypeError: Cannot read property 'addEventListener' of null

未捕获的类型错误:无法读取 null 的属性“addEventListener”

Why is this happening

为什么会发生这种情况

Browser: chrome

浏览器:铬

回答by Tushar

As you've said that scriptis loaded in headtag, by the time when the statement

正如你所说,script加载在head标签中,当语句

var b = document.getElementById('evt');

is executed, there is no element in the DOMhaving id evt.

被执行时,DOMid 中没有元素evt

Use DOMContentLoadedevent to add event listeners on element. This will run after the DOMis completely loaded.

使用DOMContentLoadedevent 在元素上添加事件侦听器。这将在DOM完全加载后运行。

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event - load - should be used only to detect a fully-loaded page. It is an incredibly popular mistake for people to use load where DOMContentLoaded would be much more appropriate, so be cautious.

DOMContentLoaded 事件在初始 HTML 文档完全加载和解析后触发,无需等待样式表、图像和子框架完成加载。一个非常不同的事件 - 加载 - 应该只用于检测完全加载的页面。人们在 DOMContentLoaded 更合适的地方使用 load 是一个非常流行的错误,所以要小心。

Code:

代码:

document.addEventListener("DOMContentLoaded", function(event) {
    var b = document.getElementById('evt');
    b.addEventListener('click', eventDemo, false);
});

回答by Hari Ram

The error itself clearly explains! You don't have any html element with the id 'evt'. If you are sure you have an element with id 'evt', then use $(document).readyas given below, so that, your js gets executed when the html elements are loaded.

错误本身清楚地解释了!您没有任何带有 id 'evt' 的 html 元素。如果您确定您有一个 id 为 'evt' 的元素,请$(document).ready按如下所示使用,以便在加载 html 元素时执行您的 js。

$(document).ready(function(){
var b = document.getElementById('evt');

var eventDemo = function(event) {

    console.log('I handled the event');
    console.log(event);
    console.log(Object.prototype.toString.call(event)); 

var imgElement = document.createElement('img');
imgElement.src = 'http://lorempixel.com/150/150/';
document.body.appendChild(imgElement);

};

b.addEventListener('onclick', eventDemo, false);
});

回答by Bart?omiej Zalewski

At the point when this script runs, the element with id 'evt' is not defined. There are two possibilities:

在此脚本运行时,未定义 id 为 'evt' 的元素。有两种可能:

  1. You misspelled the id or forgot to add it, double-check it
  2. You load this code before the page gets rendered. You say, you load this script from script.js, so it probably happens in <head>. But when the script is loaded, the <body>still isn't.
  1. 您拼错了 ID 或忘记添加它,请仔细检查
  2. 在页面呈现之前加载此代码。你说,你从 加载这个脚本script.js,所以它可能发生在<head>. 但是当脚本加载时,<body>仍然不是。

Either add this script at the bottom of the page, or, better, use the DOMContentLoadedevent:

在页面底部添加此脚本,或者更好地使用DOMContentLoaded事件:

document.addEventListener("DOMContentLoaded", function(event) { 
  //place all your code here
});

And, as somebody already mentioned, the event is called click, not onclick. The onclickis a DOM property, say, an equivalent in HTML to addEventListener.

而且,正如有人已经提到的,该事件被称为click,而不是onclick。该onclick是一个DOM属性,比如,等效在HTML中addEventListener

Should you ever happen to use jQuery, the convenient wrapper is $(document).ready(function() { /* place hode here */ });

如果您碰巧使用过 jQuery,那么方便的包装器是 $(document).ready(function() { /* place hode here */ });

回答by Nathanael Smith

From mdn

来自mdn

element = document.getElementById(id);

element is a reference to an Element object, or nullif an element with the specified ID is not in the document.

element 是对 Element 对象的引用,如果具有指定 ID 的元素不在文档中,则为null

In your case b is not found and returning null. Null is not an object so it cannot have addEventListener

在您的情况下,找不到 b 并返回 null。Null 不是一个对象,所以它不能有addEventListener

回答by sameepsi

I was getting the same kind of error and I wasted my 2 days on the same. Later found out that the same application was working fine on firefox. So I tried updating my chrome version to 53.x.x And now no such issue is occurring. Maybe this will help you too :)

我遇到了同样的错误,我浪费了 2 天的时间。后来发现同一个应用程序在 Firefox 上运行良好。所以我尝试将我的 chrome 版本更新到 53.xx 现在没有发生这样的问题。也许这也会帮助你:)