JavaScript 中 Cannot set property 'disabled' of Null 错误
出现“Cannot set property 'disabled' of Null”错误的原因有两个:
-
将
disabled
属性设置为空值(不存在的 DOM 元素)。 - 将 JS 脚本标记放在声明 DOM 元素的 HTML 上方。
下面是产生上面错误的一个示例代码
const button = null;
// ⛔️ Uncaught TypeError: Cannot set properties of null (setting 'disabled')
button.disabled = true;
要解决“Cannot set property 'disabled' of Null”错误,请确保我们用于访问元素的 ID 存在于 DOM 中。 该错误通常发生在向 getElementById
方法提供不存在的 id 之后。
const button = document.getElementById('does-not-exist');
console.log(button); // 👉️ null
// ⛔️ Cannot set properties of null (setting 'disabled')
button.disabled = true;
我们将一个不存在的 id 传递给 getElementById
方法并得到一个空值。
将
disabled
属性设置为空值会导致错误。
要解决“Cannot set property 'disabled' of null”的错误,将 JS script 标签放在 body 标签的底部。 该脚本应在创建 DOM 元素后运行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ BAD - script is run before button exists ⛔️ -->
<script src="index.js"></script>
<button id="btn">Submit</button>
</body>
</html>
我们将 JS 脚本标记放在创建按钮元素的代码上方。 这意味着 index.js
文件在创建按钮之前运行,因此我们无权访问 index.js 文件中的按钮元素。
const button = document.getElementById('btn');
console.log(button); // 👉️ null
// ⛔️ Cannot set properties of null (setting 'disabled')
button.disabled = true;
JS 脚本标签应该移到正文的底部,在它需要访问的所有 DOM 元素之后。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="btn">Submit</button>
<!-- ✅ GOOD - button already exists ✅ -->
<script src="index.js"></script>
</body>
</html>
现在,index.js 文件可以访问 button
元素。
const button = document.getElementById('btn');
console.log(button); // 👉️ button#btn
// ✅ Works
button.disabled = true;
总结
尝试将 disabled
属性设置为 null
时,会出现“Cannot set property 'disabled' of null”错误。
要解决该错误,请在 DOM 元素可用后运行 JS 脚本,并确保只在有效的 DOM 元素上设置该属性。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。