JavaScript 中 Cannot read property 'addEventListener' of Null 错误
发生“Cannot read property 'addEventListener' of Null”错误的主要原因有两个:
-
在 DOM 中不存在的元素上访问
addEventListener()
方法。 - 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。
发生错误的主要原因是当我们尝试对未找到的 DOM 元素调用 addEventListener()
方法时。
const btn = document.getElementById('does-not-exist');
console.log(btn); // 👉️ null
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
btn.addEventListener('click', () => {
console.log('btn clicked');
});
我们使用了 DOM 中不存在的 id,因此 getElementById 方法返回 null。
当我们在不存在的 DOM 元素上调用
addEventListener()
方法时,会出现错误“Cannot read property addEventListener of null
”。 要解决此错误,请在调用addEventListener()
方法之前使用 if 语句检查 DOM 元素是否存在。
const btn = document.getElementById('does-not-exist');
console.log(btn); // 👉️ null
// ✅ Check if btn exists before addEventListener()
if (btn) {
btn.addEventListener('click', () => {
console.log('btn clicked');
});
}
// ✅ Using optional chaining (?.)
btn?.addEventListener('click', () => {
console.log('btn clicked');
});
确保传递正确的标识符并添加 if 语句以检查 DOM 元素是否存在。
第二个示例使用可选的链接 ?.
运算符,它会短路而不是抛出错误。
如果 btn 变量的值为 null 或 undefined,则运算符返回 undefined,否则调用该方法。
要解决“Cannot read property addEventListener of null”错误,请确保在正文底部插入 JS 脚本标记。 JS 脚本标签应该放在 HTML 元素声明之后。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ❌ BAD - Script is run before button is declared ❌ -->
<script src="index.js"></script>
<button id="btn">Submit</button>
</body>
</html>
示例中的 JS 脚本标记位于按钮元素声明之前,因此按钮元素在 index.js 文件中将不可用。
const btn = document.getElementById('btn');
console.log(btn); // 👉️ null
// ⛔️ cannot read properties of null (reading 'addEventListener')
btn.addEventListener('click', () => {
console.log('btn clicked');
});
在声明 HTML 元素之后,我们必须将 JS 脚本标记移动到正文的底部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="btn">Submit</button>
<!-- ✅ GOOD - HTML is already declared ✅ -->
<script src="index.js"></script>
</body>
</html>
现在 index.js 文件可以访问 DOM 元素,因为它们已经在脚本运行时声明了。
const btn = document.getElementById('btn');
console.log(btn);
// ✅ Works as expected
btn.addEventListener('click', () => {
console.log('btn clicked');
});
按钮元素位于加载 index.js 文件的脚本上方,因此其代码在脚本之前运行。
找到按钮元素并且
getElementById
方法返回实际元素而不是 null,因此我们可以调用该元素的addEventListener
方法并附加一个事件侦听器。
总结
尝试对 DOM 中不存在的元素调用 addEventListener()
方法时,会发生“Cannot read property 'addEventListener' of Null”错误。
当元素不存在于 DOM 中时,存储 null 值的变量通常从 getElementById()
等方法返回。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。