使用 jQuery 访问绑定到事件处理程序的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2388030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:24:02  来源:igfitidea点击:

Accessing functions bound to event handlers with jQuery

jqueryeventsevent-handlingstorageinternal

提问by googletorp

With jQuery you can bind functions to an event triggered on a DOM object using .bind()or one of the event handler helper functions.

使用 jQuery,您可以使用.bind()或 事件处理程序辅助函数之一将函数绑定到在 DOM 对象上触发的事件。

jQuery have to store this internally somehow and I wonder if is it possible given a DOM object, to find out which events have been bound to the object, and access those functions etc. The desired return result could look something like this:

jQuery 必须以某种方式在内部存储它,我想知道是否有可能给定一个 DOM 对象,找出哪些事件已绑定到该对象,并访问这些函数等。所需的返回结果可能如下所示:

{
  click: [function1, function2],
  change: [function3],
  blur: [function4, function5, function6]
}

采纳答案by PatrikAkerstrand

Edit: the method below works only in jQuery < 1.7

编辑以下方法仅适用于 jQuery < 1.7

You can find a lot of interesting tips and tricks in this article: Things you may not know about jQuery.

您可以在本文中找到许多有趣的提示和技巧:您可能不知道的关于 jQuery 的事情

It seems that jQuery uses datato store event handlers:

似乎 jQuery 用于data存储事件处理程序:

You can access all event handlers bound to an element (or any object) through jQuery's event storage:

您可以通过 jQuery 的事件存储访问绑定到元素(或任何对象)的所有事件处理程序:

// List bound events:
console.dir( jQuery('#elem').data('events') );

// Log ALL handlers for ALL events:
jQuery.each($('#elem').data('events'), function(i, event){
    jQuery.each(event, function(i, handler){
        console.log( handler['handler'].toString() );
    });
});

// You can see the actual functions which will occur
// on certain events; great for debugging!

回答by eikes

jQuery 1.7 has stopped exposing the events in the regular data() function. You can still get them like this:

jQuery 1.7 已停止在常规 data() 函数中公开事件。你仍然可以像这样得到它们:

var elem = $('#someid')[0];
var data = jQuery.hasData( elem ) && jQuery._data( elem );
console.log(data.events);

Please note, that this only works for Events which have been bound using jQuery. AFAIK you there is no way to see all the events which have been bound using the regular DOM functions like addEventListener.

请注意,这仅适用于使用 jQuery 绑定的事件。AFAIK 你没有办法看到所有使用像 addEventListener 这样的常规 DOM 函数绑定的事件。

You can see them in the webkit inspector though: In the Elements tab navigate to the desired DOM node, on the right side select the "Event Listeners" drop down.

不过,您可以在 webkit 检查器中看到它们:在 Elements 选项卡中导航到所需的 DOM 节点,在右侧选择“Event Listeners”下拉列表。