jQuery: Can I get a reference to the bound events on an element?
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');
Questions You Might Ask
Why don't you just change the code that's binding it to the click event?
开发者_如何学GoThe 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.
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');
}
Try this:
jQuery('#element').data('events');
You can also do this:
jQuery.each(jQuery('#element').data('events'), function(i, event){
jQuery.each(event, function(i, eventHandler){
console.log("The handler is " + eventHandler.toString() );
});
});
精彩评论