首页 > 解决方案 > 监听未附加元素的点击事件

问题描述

我想收听动态创建且未附加的元素上的点击事件。看这个例子:

document.addEventListener('click', function(e){
  if(e.target.tagName == 'BUTTON'){
    console.log('Click');
  }
});
document.createElement('button').click();
<button>Test</button>

创建元素并在其上使用 click 方法时不会调用侦听器。

为什么会这样,我该如何收听这些事件?

谢谢!

标签: javascript

解决方案


如评论中所述,要么覆盖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();

请注意,像这样覆盖重要的内置对象和方法是非常棘手的,并且不适合在严肃的生产代码中使用 - 只有当您没有其他选择时才需要考虑,例如在用户脚本的不寻常环境中。


推荐阅读