一旦在jQuery中绑定了一个事件,你如何获得对事件处理函数的引用? [英] Once an event is bound in jQuery how do you get a reference to the event handler function?

查看:80
本文介绍了一旦在jQuery中绑定了一个事件,你如何获得对事件处理函数的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我附加了一个点击事件处理程序:

If I attach a click event handler:

$(".selector").bind("click", function () {
  // some handler function
});

如何获得对该功能的引用?这不起作用:

How can I get a reference to that function? This doesn't work:

var refToFunc = $(".selector").bind("click");
typeof refToFunc === "object";  // I want the function

我认为 bind(eventname)在这种情况下只返回jQuery对象而不是事件处理函数。它必须存储在某处。

I think bind("eventname") in that case just returns the jQuery object and not the event handler function. It must be stored somewhere.

推荐答案

非常有趣的问题。您可以这样检索它:

Very interesting question. You can retrieve it like this:

var refToFunc = $(".selector").data("events")["click"][0].handler;

请注意,我们使用 [0] 因为你有一个处理程序数组,以防你绑定多个处理程序。对于其他活动,只需更改为活动名称。

Note that we used [0] because you have an array of handlers, in case you bound more than one handler. For other events, just change to the event name.

编辑
通常,您可以使用以下插件获取所有内容事件的所选元素的处理程序(代码尚未优化):

EDIT In general, you could use the following plugin to get all handlers of the selected elements for an event (code not optimized yet):

$.fn.getEventHandlers = function(eventName){
  var handlers = [];
  this.each(function(){
     $.each($(this).data("events")[eventName], function(i, elem){
         handlers.push(elem.handler);    
     });     
  });
  return handlers;
};

如何使用?:

$(".selector").getEventHandlers("click");

它将返回包含所有事件处理程序的函数数组。

And it would return an array of functions containing all event handlers.

针对您的具体问题,您可以像这样使用此插件:

For your specific question, you could use this plugin like this:

var refToFunc = $(".selector").getEventHandlers("click")[0];

希望这会有所帮助。欢呼声

Hope this helps. cheers

这篇关于一旦在jQuery中绑定了一个事件,你如何获得对事件处理函数的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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