有这样一个答案:我可以通过编程方式检查和修改 html 元素上的 Javascript 事件处理程序吗? https://stackoverflow.com/questions/1436823/can-i-programmatically-examine-and-modify-javascript-event-handlers-on-html-elem但它不提供运行时解决方案
没有任何直接的 API 可以实现这一点,但可以通过一种侵入式的方式访问它。
通过覆盖HTMLElement.prototype.addEventListener
例如,我们可以捕获添加的事件并将它们存储在数组中。
const listeners = []
const originalAddEventListener = HTMLElement.prototype.addEventListener
HTMLElement.prototype.addEventListener = function(type, listener, options) {
listeners.push({
element: this,
type,
listener,
options
})
// call the original listener with current this and provided arguments
return originalAddEventListener.call(this, type, listener, options)
}
完整片段和示例:
const listeners = []
const originalAddEventListener = HTMLElement.prototype.addEventListener
HTMLElement.prototype.addEventListener = function(type, listener, options) {
listeners.push({
element: this,
type,
listener,
options
})
return originalAddEventListener.call(this, type, listener, options)
}
document.querySelector('p').addEventListener('click', () => {
console.log('clicked')
}, false)
document.querySelector('button').addEventListener('click', () => console.log(listeners))
p {
width: 100px;
height: 100px;
background: red;
color: white;
}
<button>list listeners</button>
<p>click me</p>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)