简体   繁体   中英

JavaScript/jQuery: event fired twice

I'm trying some event bindings with jQuery, and I have this simple code in my document ready:

$(document).ready(function() {
    $("p a").each(function(i, selected){
        $(selected).hover(
            function(event) { alert('over: ' + event.type); },
            function(event) { alert('out: ' + event.type); });
        }
    )
});

So, when I move mouse over a link thats inside a paragraph (selector is "pa") alerts pop-up twice. So, mouseenter and mouseleave are fired twice.

This only happens in Google Chrome. In Internet Explorer 7, Firefox 3, Opera and Safari both events are fired only once.

Why is this happening?

I suppose this doesn't answer your question, but this post came up while researching my own bug. It turned out the problem was that I had inadvertently included an external javascript twice.

Just thought it would be worthwhile to document this for others who have the same problem. An obvious error that took a while to track down!

I think somehow the alert is actually causing the extra events in Chrome. With the following code I only see one event.

$(document).ready(function() {
  $("p a").each(function(i, selected){
    $(selected).hover( 
      function(event) { $("p").append('<br>over: ' + event.type); }, 
      function(event) { $("p").append(' out: ' + event.type); });
    }
  )
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM