偶尔看到了这个问题,如何用JS获取元素某一事件上绑定的所有Listener?
突然觉得好像是有解决办法的,查了下,在 chrome 下,支持
window.getEventListeners(obj)
例如:
addEvent(aLink, 'click',f, false); window.getEventListeners(aLink)
返回:
如果要模仿 chrome 实现呢,也是可以的,需要修改 addEventListener 和 removeEventListener,或者你自己自定义一个也行,比如我实现后的效果:
基本上是模仿了,chrome 定义的全局方法,我是绑定在每一个事件对象的属性上,通过 obj.eventList 来访问,具体代码如下:
var aLink = document.links[0]; function addEvent(obj, type, callback, useCapture) { obj.addEventListener(type, callback, useCapture); addEventList(obj, type, callback, useCapture); } function removeEvent (obj, type, callback, useCapture) { obj.removeEventListener(type, callback, useCapture); removeEventList(obj, type, callback, useCapture); } function addEventList(obj, type, callback, useCapture) { if (obj.eventList) { if (obj.eventList[type]) { obj.eventList[type].push({ callback: callback, useCapture: useCapture }); } else { obj.eventList[type] = [{ callback: callback, useCapture: useCapture }]; } } else { obj.eventList = {}; obj.eventList[type] = [{ callback: callback, useCapture: useCapture }]; } } function removeEventList(obj, type, callback, useCapture) { var eventList=obj.eventList; if (eventList) { if (eventList[type]) { for (var i = 0; i < eventList[type].length; i++) { if (eventList[type][i].callback===callback) { eventList[type].splice(i, 1); if (eventList[type].length===0) { delete eventList[type]; } break; } } } } } function f () { event.preventDefault(); alert('f'); } function g () { event.preventDefault(); alert('g'); } function h () { event.preventDefault(); alert('h'); } addEvent(aLink, 'click', f, false); addEvent(aLink, 'click', g, false); addEvent(aLink, 'mouseup', h, false); console.log(aLink.eventList);