javascript - 监听未附加元素的点击事件
问题描述
我想收听动态创建且未附加的元素上的点击事件。看这个例子:
document.addEventListener('click', function(e){
if(e.target.tagName == 'BUTTON'){
console.log('Click');
}
});
document.createElement('button').click();
<button>Test</button>
创建元素并在其上使用 click 方法时不会调用侦听器。
为什么会这样,我该如何收听这些事件?
谢谢!
解决方案
如评论中所述,要么覆盖HTMLButtonElement.prototype.click
:
const nativeClick = HTMLButtonElement.prototype.click;
HTMLButtonElement.prototype.click = function(...args) {
console.log('Click');
nativeClick.apply(this, args);
};
document.createElement('button').click();
或者,一种稍微不同(效率较低)的方法是覆盖Document.prototype.createElement
,以便新创建button
的 s 获得附加到它们的侦听器:
const nativeCreateElement = Document.prototype.createElement;
Document.prototype.createElement = function(...args) {
const createdElement = nativeCreateElement.apply(this, args);
if (typeof args[0] === 'string' && args[0].toLowerCase() === 'button') {
createdElement.addEventListener('click', () => {
console.log('Click');
});
}
return createdElement;
}
document.createElement('button').click();
请注意,像这样覆盖重要的内置对象和方法是非常棘手的,并且不适合在严肃的生产代码中使用 - 只有当您没有其他选择时才需要考虑,例如在用户脚本的不寻常环境中。
推荐阅读
- dataset - 有人可以帮我找到满足以下要求的数据集吗?
- flutter - 如何添加如图所示的弯曲模态底片?如何在其上方添加关闭按钮?飘飘然
- r - 使用 case_when() 和 filter() 根据 R 中一列中的值和另一列中的级别对数据帧进行子集化
- mysql - 为什么我的 SQL FOREIGN KEY 子句返回错误?
- javascript - 即使 gtag 是窗口对象的一部分,Javascript 也会抛出“Uncaught TypeError: gtag is not a function”
- unity3d - Unity 中的 GPGS 设置 - 构建错误
- google-drive-api - 检查 google drive 文件是否是 Google Docs、Sheets 和 Slides?
- python - 在 Python 中将混合数据类型转换为数值
- python - 从无 Python 引发 JSONDecodeError("Expecting value", s, err.value)
- c# - c# REST API 中本机 /desktop 应用程序的 Keycloack 无法正常工作还是我遗漏了什么?