jQuery:我可以获得对元素绑定事件的引用吗?
我有一些元素与click
事件绑定了一个函数。 我想将相同的函数绑定到mouseover
和mouseout
事件。 是否可以获得对click事件的引用,以便我可以将其分配给其他事件? 我在想象这样的东西(在each()
里面:
$(this).bind('mouseover', $(this).click()); $(this).bind('mouseout', $(this).click()); $(this).unbind('click');
你可能会问的问题
为什么不直接更改将其绑定到click事件的代码?
设置它的JS是Drupal模块的一部分( DHTML菜单 ,如果你很好奇),所以我不想更改模块代码,因为当模块将来不可避免地更新时它将被清除。 我也在页面的其他部分使用click
处理程序 – 我只想将mouseover
移到mouseover
移动一个菜单。
在jQuery中,jQuery绑定的所有事件都存储在关键events
下的data
。 以下将做你想要的:
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('#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() ); }); });