【问题标题】:jQuery: Can I get a reference to the bound events on an element?jQuery:我可以获得对元素上绑定事件的引用吗?
【发布时间】:2010-02-08 18:10:37
【问题描述】:

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

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

您可能会问的问题

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

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

在 jQuery 中,所有被 jQuery 绑定的事件都存储在 dataevents 键下。以下将做你想做的事:

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');
}

【讨论】:

  • 仅供其他人参考,在 jquery 1.8 中已删除。 .data('events') 不可用。
  • 在 jquery 1.8 中,您仍然可以使用 $._data(element, "events") 访问事件字典,但这可能随时更改。
  • 如果我想查找不仅由 jQuery 绑定的所有事件,而且还与其他方法/进程绑定。
【解决方案2】:

试试这个:

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() );
    });
});

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多