0

我是一名试图为新项目学习编程的艺术家/

我正在尝试创建一个程序,其中仅在调用函数的前三次触发鼠标退出警报。这是我的代码。目前,它被触发了 3 次:

<!DOCTYPE html>
<html>
<head>
</head>

<body>

    <div id="message">
   <input type="button" value="CLICK HERE" id="countButton" />

    <p style="color: white">The button was pressed <span id="displayCount">0</span> times.</p>
    </div>
    <script type="text/javascript">
      var count = 0;
      var button = document.getElementById("countButton");
      var display = document.getElementById("displayCount");



      button.onclick = function(){
        count++;
        display.innerHTML = count;

        if (count <=3){
          button.onmouseout = function () {
            alert("        Come on... BACK TO WORK!");
          }
        }

        else if(count>3){
        document.body.innerHTML=""
        alert("FINALLY!!!");
}
      }
    </script>
</body>
</html>

那是该程序的较短版本。您可以在下面的链接中看到最终结果(减去 mouseout 问题):http ://www.esmeraldakosmatopoulos.com/blank#!/ c1fam 警告:这很烦人......故意的。

请帮我

谢谢!

4

1 回答 1

0

这里的基本问题是else代码的一部分。mouseout每次单击按钮时,它都会重新附加一个处理程序count <= 3

您需要移出button.onmouseout = {...}处理onclick程序,然后进入elseput button.onmouseout = null;

但是,我建议您使用addEventListener()而不是事件属性。要删除侦听器,您可以使用removeEventListener()这种方式,您可以更好地控制事件处理。

于 2013-06-24T15:42:28.677 回答