简体   繁体   English

JavaScript / jQuery:事件被触发两次

[英]JavaScript/jQuery: event fired twice

I'm trying some event bindings with jQuery, and I have this simple code in my document ready: 我正在尝试使用jQuery进行一些事件绑定,并且在我的文档中准备好了这个简单的代码:

$(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. 因此,当我将鼠标移动到段落内的链接(选择器为“pa”)时,会弹出两次警报。 So, mouseenter and mouseleave are fired twice. 因此,mouseenter和mouseleave被激发两次。

This only happens in Google Chrome. 这只发生在Google Chrome中。 In Internet Explorer 7, Firefox 3, Opera and Safari both events are fired only once. 在Internet Explorer 7, Firefox 3, OperaSafari中,这两个事件仅触发一次。

Why is this happening? 为什么会这样?

I suppose this doesn't answer your question, but this post came up while researching my own bug. 我想这不会回答你的问题,但这篇文章是在研究我自己的bug时提出来的。 It turned out the problem was that I had inadvertently included an external javascript twice. 原来问题是我无意中包含了两次外部JavaScript。

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. 我认为警报实际上导致了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); });
    }
  )
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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