gpt4 book ai didi

Javascript:为什么我会收到此 Uncaught TypeError:无法读取 null 的属性 'addEventListener'?

转载 作者:行者123 更新时间:2023-11-28 11:53:21 25 4
gpt4 key购买 nike

我正在尝试注册一个事件处理程序,当按钮触发单击事件时,该事件处理程序会将元素附加到 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);

但我不断得到:

Uncaught TypeError: Cannot read property 'addEventListener' of null

为什么会出现这种情况

浏览器:chrome

最佳答案

正如您所说,当语句出现时,script 已加载到 head 标记中

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

执行后,DOM 中不存在 id evt 的元素。

使用DOMContentLoaded event 在元素上添加事件监听器。这将在 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.

代码:

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

关于Javascript:为什么我会收到此 Uncaught TypeError:无法读取 null 的属性 'addEventListener'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com