jQuery:是否可以引用元素上的绑定事件? [英] jQuery: Can I get a reference to the bound events on an element?

查看:86
本文介绍了jQuery:是否可以引用元素上的绑定事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some elements with a function bound to the click event. I want to bind that same function instead to the mouseover and mouseout events. Is it possible to get a reference to the click event so that I can assign it to those other events? I'm imagining something like this (inside each()):

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

您可能会问的问题

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

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

The JS that's setting this up is part of a Drupal module (DHTML Menu, if you're curious), so I don't want to change the module code because it will be wiped out when the module is inevitably updated in the future. I'm also using the click handler for other parts of the page - I only want to move it to mouseover and mouseout for one menu.

推荐答案

在jQuery中,由jQuery绑定的所有事件都存储在data中的键events下.以下将满足您的要求:

In jQuery, all the events bound by jQuery are stored in data under the key events. The following would do what you want:

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:是否可以引用元素上的绑定事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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