【发布时间】:2022-07-13 00:18:35
【问题描述】:
有这个答案:can I programmatically examine and modify Javascript event handlers on html elements? 但它不提供运行时解决方案
【问题讨论】:
标签: javascript javascript-events
有这个答案:can I programmatically examine and modify Javascript event handlers on html elements? 但它不提供运行时解决方案
【问题讨论】:
标签: javascript javascript-events
没有任何直接的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)
}
完整的 sn-p 示例:
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>
【讨论】: