【问题标题】:prevent hover from triggering event twice防止悬停触发事件两次
【发布时间】:2015-03-18 13:42:36
【问题描述】:

当一个 div 悬停在上面时,我正在尝试获得一个提醒来工作。

http://jsfiddle.net/4RgTS/248/

我当前的代码是(对于名为“testdiv”的 div)

$(document).ready(function() {
    $("#testdiv").hover(function() {
        alert('1');
    });
});

这有效并显示警报,但在下一次鼠标移动时,即使我没有将鼠标悬停在 div 上,警报也会再次显示?

一如既往的感谢,

【问题讨论】:

    标签: jquery hover jquery-hover


    【解决方案1】:

    您可以使用$.one 事件来处理此问题:

    $(document).ready(function() {
      $("#testdiv").one("mouseenter",
        function() {
          alert('1');
        });
    });
    #testdiv {background: #ccf;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div id="testdiv">Hover Me!!!</div>

    或者,如果我没有正确回答您的问题,您只需使用 mouseenter 事件即可。

    $(document).ready(function() {
      $("#testdiv").on("mouseenter",
        function() {
          alert('1');
        });
    });
    #testdiv {background: #ccf;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div id="testdiv">Hover Me!!!</div>

    【讨论】:

      【解决方案2】:

      这是因为如果只将一个处理函数传递给hover(),它会同时用于mouseentermouseleave 事件。要获得您想要的行为,请更改为仅使用 mouseenter

      $("#testdiv").mouseenter(function () {
          alert('1');
      });
      

      Updated fiddle

      【讨论】:

      • 当我再次将鼠标悬停在它上面时,它也是如此。
      • 没错。如果您只希望它触发一次,请使用.one('mouseover', function() {...
      • 是的,好吧,我问错了问题。也更新了我的答案! :)
      【解决方案3】:

      我相信你在这里只想要.mouseenter() 事件:

      $("#testdiv").mouseenter(function() {
            alert('1');
      });
      

      Working Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        • 2013-05-16
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        • 2021-01-22
        相关资源
        最近更新 更多