jQuery:我可以获得对元素绑定事件的引用吗?

Bro*_*and 8 javascript jquery

我有一些元素与click事件绑定的函数.我想将相同的函数绑定到mouseovermouseout事件.是否可以获得对click事件的引用,以便我可以将其分配给其他事件?我在想象这样的东西(里面each()):

$(this).bind('mouseover', $(this).click());
$(this).bind('mouseout', $(this).click());
$(this).unbind('click');
Run Code Online (Sandbox Code Playgroud)

你可能会问的问题

为什么不直接更改将其绑定到click事件的代码?

设置它的JS是Drupal模块的一部分(DHTML菜单,如果你很好奇),所以我不想更改模块代码,因为当模块将来不可避免地更新时它将被清除.我还使用了click该页面的其他部分的处理程序-我只是想将它移动到mouseovermouseout一个菜单.

Dou*_*ner 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');
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供其他人未来参考,这已经在jquery 1.8中被删除了..data('events')不可用. (9认同)
  • 在jquery 1.8中,您仍然可以使用`$ ._ data(element,"events")`访问事件字典,但这可能随时发生变化. (8认同)