【问题标题】:Javascript: alert checking for mouseover and mouseout firing multiple timesJavascript:多次触发鼠标悬停和鼠标悬停的警报检查
【发布时间】:2011-06-12 03:37:53
【问题描述】:

编写执行以下操作的代码:

  1. 在加载时向网页添加鼠标侦听器
  2. 检查鼠标位于哪个元素上
  3. 如果鼠标位于锚标记上,则在离开前在该位置停留一段时间后执行特定功能。现在我只是随意使用 10000 毫秒

下面是我用作测试平台的示例代码

<html>
<head></head>
<title>A test page</title>
<body>

    <script type='text/javascript'>
    document.addEventListener("mouseover", checkElement, false);

    function checkElement(ev){
         var elm = ev.target || ev.srcElement;
            if(elm.tagName === 'A'){
            var focusTime = new Date().getTime();
            elm.addEventListener("mouseout", function() {tellTime(focusTime)}, false);
         }
    }

    function tellTime(focusTime){
        var blurTime = new Date().getTime();
        if ((blurTime - focusTime) > 10000) {
            alert ('You spent a long time there');
        }
    }
    </script>

    <a href="www.google.co.in">This is a hyperlink</a>
    <p> This is just some bloody text </p>
</body>

</html>

在测试时我发现当警报被触发时,它会被触发多次;两次、三次甚至更多。我想知道为什么会发生这种情况,以及我可以做些什么来避免为同一元素多次触发警报。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您正在向元素添加多个mouseout 事件。

    您将需要取消绑定前一个,或正常分配它并让focusTime 作用于这两个函数。

    【讨论】:

    • 分配它通常意味着不取消绑定之前的事件吗?
    【解决方案2】:

    重复事件绑定...试试下面的代码。

    <html>
    <head></head>
    <title>A test page</title>
    <script type='text/javascript'>
        document.addEventListener("mouseover", checkElement, false);
    
        function checkElement(ev){
            var elm = ev.target || ev.srcElement;
            if(elm.tagName === 'A'){
                var focusTime = new Date().getTime();
                elm.addEventListener("mouseout", tellTime, false);
            }
            function tellTime(){
                elm.removeEventListener("mouseout", tellTime, false);
                var blurTime = new Date().getTime();
                if ((blurTime - focusTime) > 2000) {
                    alert ('You spent a long time there');
                }
            }
    }
    
    
    </script>
    <body>
        <a href="www.google.co.in">This is a hyperlink</a>
        <p> This is just some bloody text </p>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 2011-08-04
      • 2018-09-03
      • 1970-01-01
      • 2013-07-16
      相关资源
      最近更新 更多