本文详解 addEventListener 的基本用法与常见错误,重点解决因 DOM 元素未获取成功(返回 null)导致的 “Cannot read properties of null” 报错,并提供安全、健壮的事件绑定实践方案。
本文详解 `addeventlistener` 的基本用法与常见错误,重点解决因 dom 元素未获取成功(返回 null)导致的 “cannot read properties of null” 报错,并提供安全、健壮的事件绑定实践方案。
在 JavaScript 中,addEventListener() 是为 DOM 元素绑定事件监听器的标准方法,支持解耦、复用和灵活控制(如事件捕获/冒泡、一次性监听等)。但初学者常因执行时机或选择器错误,导致获取元素失败,进而触发类似以下报错:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
该错误本质是:你试图对 null 值调用 .addEventListener() —— 而 null 通常源于 document.getElementById()、querySelector() 等方法未找到对应元素,返回了 null。
✅ 正确用法:确保元素存在且脚本执行时机恰当
HTML 示例:
<title>Event Listener Demo</title><button id="startBtn">Start Test</button> <button id="stopBtn">Stop Test</button> <!-- 推荐:将 script 放在 body 底部 --> <script src="script.js"></script>
JavaScript(script.js):
// ✅ 安全写法 1:先检查元素是否存在
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
if (startBtn) {
startBtn.addEventListener('click', startTest);
} else {
console.warn('⚠️ #startBtn not found in DOM');
}
if (stopBtn) {
stopBtn.addEventListener('click', stopTest);
} else {
console.warn('⚠️ #stopBtn not found in DOM');
}
function startTest() {
console.log('Test started!');
}
function stopTest() {
console.log('Test stopped!');
}
⚠️ 关键注意事项
-
执行时机问题:若 <script> 标签位于 <head> 中,而 DOM 尚未加载完成,getElementById 将返回 null。解决方案有三:</script>
- 将 <script> 移至 </script>










