jQuery events: prepend a callback handler to already existing ones

删除回忆录丶 提交于 2019-12-01 23:27:50

问题


On a web page are elements with click and/or keypress handlers. If I add a new one it would be executed after them. I need a way to add a new callback which is prepended to the event handler list, so that it is executed beforehand. How is that possible with jQuery?

Update

Why can't I just use jQuery's unbind method? I am injecting my jQuery code to any web page, so that i don't know if any and which JavaScript framework is used. I need a universal way to detect event handlers and prepend mine. (Before you ask, I'm building a "recorder" application that tracks the users actions to store them and to execute them later on.)

Update 2

I only use Firefox, no need for IE compatibility. I have to wait for the page to load completely, and after that my jQuery script will be invoked.


回答1:


I think this might work if you use event capturing (the handlers of ancestors are called before the event reaches the element) instead of bubbling (child --> ancestors). This is a way to intercept an event before the target element is reached.

Most event handlers use event bubbling. According to w3c an event first gets captured, and then from the target it bubbles up again. So if you would bind an event to the document using capturing it would be executed first for every element on the page.

http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-flow-capture

You would bind the handler with: (the third argument is whether you want to use event capturing)

document.body.addEventListener('click',handler,true)

This would be executed for every click in the element, before the event handler of the clicked element is executed. I am not sure though about support in browsers.



来源:https://stackoverflow.com/questions/9052349/jquery-events-prepend-a-callback-handler-to-already-existing-ones

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