Rob*_* M. 5 javascript jquery event-handling javascript-events
我正在为我的大学做一个项目.我需要做的一件事是将所有已注册的javascript-eventhandler与服务器同步.即我需要知道哪些元素具有特定的事件处理程序.
我已经使用VisualEvent来找出哪些元素有事件处理程序,它的工作真的很棒.
但我需要的是拥有一个事件监听器,每次为DOM元素注册事件处理程序时都会调用该事件监听器.
所以基本上每次像$("#foo").click(...)或$("#foo").bind(...)叫,我需要的是一个新的事件处理程序已经注册该元素的信息.
反之亦然当从DOM元素中删除事件处理程序时,我需要一个侦听器,但这对于第一个原型不是必需的.
有没有办法可以将处理程序全局附加到所有事件处理程序注册?
如果您需要更多信息,请随时发表评论.
在此先感谢您的帮助!
最好的问候,罗伯特
如果你正在使用jQuery 1.7+,所有附加事件的方法都会通过jQuery.fn.on,所以这是一个简单的例子,它可以覆盖这个函数并且变得疯狂;
(function () {
var old = jQuery.fn.on;
jQuery.fn.on = function (events, selector, data, handler) {
// Ensure you still attach the events
var result = old.apply(this, arguments);
// Now do your own thing
// Inside here, `this` refers to the jQuery object on which `on` was invoked;
// it's not a specific element like it normally is within jQuery. You then
// therefore use something like `this.each(function () { /* this */ }); to
// target each element in the set.
// You might want to normalize the variables, as selector and data are optional,
// and events can be an object or string
jQuery.post('/spy.php', {
events: events,
selector: selector,
data: data
}, jQuery.noop);
return result; // keep the signature of `on`, and return the value `on()` *would* have done.
};
}());
Run Code Online (Sandbox Code Playgroud)
如果你正在使用jQuery <1.7且不能升级,你可以做一些类似上述的东西,但一定要覆盖bind(),live(),delegate()等.