jQuery事件:将回调处理程序预置到已存在的事件 [英] jQuery events: prepend a callback handler to already existing ones

查看:86
本文介绍了jQuery事件:将回调处理程序预置到已存在的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网页上有点击和/或按键处理程序的元素。如果我添加一个新的,它会执行后,他们。我需要一种方法来添加一个新的回调,它是事件处理程序列表的前面,所以它被预先执行。如何使用jQuery?

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?

更新

只是使用jQuery的unbind方法?我注入我的jQuery代码到任何网页,所以我不知道是否有任何JavaScript框架使用。我需要一个通用的方式来检测事件处理程序和预处理我的。 (在你问之前,我正在建立一个记录器应用程序,跟踪用户的操作以存储它们并在以后执行它们。)

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.)

更新2

我只使用Firefox,不需要IE兼容性。我必须等待页面完全加载,然后我的jQuery脚本将被调用。

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.

推荐答案

如果你使用事件捕获(祖先的处理程序在事件到达元素之前调用),而不是冒泡(child - > ancestors)。这是一种在达到目标元素之前拦截事件的方法。

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.

大多数事件处理程序都使用事件冒泡。根据w3c,事件首先被捕获,然后从目标它再次起泡。因此,如果您使用捕获将事件绑定到文档,则会首先对页面上的每个元素执行。

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)

这将在执行clicked元素的事件处理程序之前对元素中的每次点击执行。我不知道在浏览器支持。

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.

这篇关于jQuery事件:将回调处理程序预置到已存在的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆