且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript - 如何检查事件是否已添加

更新时间:2023-12-05 11:32:16

使用jquery你可以使用数据(events)在任何对象上(这里是窗口):

Using jquery you can do use data("events") on any object (here the window) :

var hasbeforeunload = $(window).data("events") && $(window).data("events").['beforeunload'];

但这仅适用于jquery添加的事件。

But this works only for jquery added events.

在更一般的情况下,您应该只是存储您在某处添加侦听器的信息:

In a more general case, you should simply store the information that you add a listener somewhere :

   var addedListeners = {};
   function addWindowListenerIfNone(eventType, fun) {
      if (addedListeners[eventType]) return;
      addedListeners[eventType] = fun;
      window.addEventListener(eventType, fun);
   }

我认为javascript中没有标准的方式来获取现有的事件处理程序。***你可以附加Node的addEventListener函数来拦截和存储监听器,但我不推荐它...

I think there is no standard way in javascript to get the existing event handlers. At best you could surcharge the addEventListener function of Node to intercept and store the listeners but I don't recommend it...

编辑:

从jQuery 1.8开始,事件数据在 $ ._ data(element,events)中可用。更改日志有一个警告应该考虑在内:

From jQuery 1.8, event data are available in $._data(element, "events"). The change log has a warning that should be taken into account :


请注意,这不是受支持的公共接口;实际数据
结构可能会因版本不同而发生变化。

Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.