最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Can I get a reference to the bound events on an element? - Stack Overflow

programmeradmin0浏览0评论

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?

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.

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?

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.

Share Improve this question asked Feb 8, 2010 at 18:10 Brock BolandBrock Boland 16.7k11 gold badges36 silver badges36 bronze badges 1
  • 1 Similar to stackoverflow.com/questions/516265/… . – user69173 Commented Feb 8, 2010 at 18:14
Add a comment  | 

2 Answers 2

Reset to default 13

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() );
    });
});
发布评论

评论列表(0)

  1. 暂无评论