jQuery:我能获取元素上绑定事件的引用吗?

8

我有一些带有绑定到click事件的函数的元素。我想将相同的函数绑定到mouseovermouseout事件中。是否可能获取对单击事件的引用,以便我可以将其分配给其他事件?我想象中的代码如下(在each()内部):

$(this).bind('mouseover', $(this).click());
$(this).bind('mouseout', $(this).click());
$(this).unbind('click');

你可能会问的问题

为什么你不直接更改绑定到点击事件的代码呢?

设置这个的JS是Drupal模块(DHTML Menu)的一部分,所以我不想更改模块代码,因为它将在未来更新模块时被清除。我还使用click处理程序来处理页面的其他部分 - 我只想将其移动到一个菜单的mouseovermouseout


1
类似于https://dev59.com/unRB5IYBdhLWcg3wxZ_Y。 - user69173
2个回答

13

在jQuery中,所有由jQuery绑定的事件都存储在data键下的events中。以下代码将实现您想要的功能:

var $this = $(this),
    events = $this.data('events');
if( events && events['click'] ){
  // Loop through each click event bound to this control
  $.each( events['click'], function(){
   // this = the function
   $this.bind('mouseover mouseout', this);
  });
  // Finally, remove all `click` handlers with one call
  $this.unbind('click');
}

9
仅供他人参考,这个在 jQuery 1.8 中已被取消。.data('events') 不再可用。 - Sam Greenhalgh
8
在 jQuery 1.8 中,你仍然可以使用 $._data(element, "events") 访问事件字典,但这可能随时会被更改。 - hughes
如果我想查找不仅由jQuery绑定的所有事件,还有其他方法/过程呢? - soham

3

试试这个:

jQuery('#element').data('events');

您也可以这样做:
jQuery.each(jQuery('#element').data('events'), function(i, event){
    jQuery.each(event, function(i, eventHandler){
        console.log("The handler is " + eventHandler.toString() );
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接