Iterate getEventListeners() return object

≯℡__Kan透↙ 提交于 2020-01-11 04:04:24

问题


I am searching for a way to iterate the object getEventListeners(obj) returns. This way, I wouldn't need specific code to iterate event listener types, or to check if they exist on the checked element. My goal is to remove some event listeners from an element. For example remove all mouse related ones, and keep the others.

Thanks


回答1:


getEventListeners() will return simple JS object, you can iterate objects like this:

var listeners = window.getEventListeners(document.body);
Object.keys(listeners).forEach(event => {
    console.log(event, listeners[event]);
});

But looks like that getEventListeners method is available only in chrome, not sure what is your use case, but you might want to use different method for getting event listeners.




回答2:


getEventListeners(obj) is only a Google Chrome specific Command Line Tool feature. This means that you can only use this feature inside Chrome Dev Tools when manually typing into the console. You cannot use this method in your actual JavaScript source code.

If you want to achieve what you described, AFAIK you have to keep track of your listeners manually. Check this answer for further instructions.



来源:https://stackoverflow.com/questions/46974675/iterate-geteventlisteners-return-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!