addEventListener
绑定 change
事件,event.target
为空的原因及解决方法
在使用 addEventListener
绑定 change
事件时,有时会遇到 event.target
为 null
的情况。本文将分析此问题的原因并提供解决方案。
问题示例:
以下代码片段演示了这个问题:
const input = document.createElement('input');
input.type = 'file';
input.accept = '.doc, .docx';
input.addEventListener('change', handleFileSelect, false);
function handleFileSelect(event) {
console.log(111, event.target); // event.target 为 null
}
在这个例子中,event.target
为 null
的原因在于:在为 input
元素添加事件监听器后,该元素尚未添加到文档中。 只有当元素存在于文档中,浏览器才能正确捕获并处理其事件,从而使 event.target
指向正确的元素。
解决方案:
将 input
元素添加到文档中即可解决这个问题。 修改后的代码如下:
const input = document.createElement('input');
input.type = 'file';
input.accept = '.doc, .docx';
input.addEventListener('change', handleFileSelect, false);
function handleFileSelect(event) {
console.log(111, event.target); // event.target 将指向 input 元素
}
document.body.appendChild(input); // 将 input 元素添加到文档中
通过 document.body.appendChild(input)
将 input
元素添加到文档的 中,
change
事件现在能够被正确触发,event.target
将正确地指向该 input
元素。 记住,在触发事件之前,必须将目标元素添加到 DOM 树中。