应该如何正确放置addeventListener

时间:2018-11-24 08:25:53

标签: javascript

当我单击按钮时,AddEventListener无效,类名在html上是正确的。

以及如何正确设置时间间隔。我希望球滚动并在给定的时间示例10s上停止。 这是html文件,下面是js代码

<!DOCTYPE html>
    <html>
    <link rel ='stylesheet' href ="style.css">
     <script src = 'main.js'></script>



 <body>
<div class = "wrapper_main" align ='center'>
 <div > This is a lotto app design sample
   <div class="ball-size">
     <img src = "numbers/ball-0.png"  class = "balls-0">
     <img src = "numbers/ball-0.png"  class = "balls-1">
     <img src = "numbers/ball-0.png"  class = "balls-2">
   </div>
  <div onclick="myFunction()" class ="buttons">
  <button class = "btn-roll"> Roll </button>
  </div>
 </div>
</div>


 </body>
</html>



js file ----

document.querySelector(".btn-roll").addEventListener("click", myFunction);
/*
        var timesRun = 0;
        var interval = setInterval(myFunction, 0);
        timesRun += 1;
        if(timesRun ===10) {
            clearInterval(interval);
        } */

function myFunction() {
  var balls, balls1, balls2;
  balls = Math.floor(Math.random() * 10);
  balls1 = Math.floor(Math.random() * 10);
  balls2 = Math.floor(Math.random() * 10);

  var ballsDOM = document.querySelector(".balls-0");
  var ballsDOM1 = document.querySelector(".balls-1");
  var ballsDOM2 = document.querySelector(".balls-2");
  ballsDOM.src = "numbers/ball-" + balls + ".png";
  ballsDOM1.src = "numbers/ball-" + balls + ".png";
  ballsDOM2.src = "numbers/ball-" + balls + ".png";
  console.log("done");
}

1 个答案:

答案 0 :(得分:0)

在创建DOM并且页面中存在button之后,进行事件竞标很重要。

例如,这将不起作用:

<body>
    <script>
        document.querySelector('.btn-roll').addEventListener('click', myFunction);

        function myFunction(){
            alert(1);
        }
    </script>
    <button class="btn-roll">click on me</button>
</body>

因为我们将事件绑定到了尚不存在的按钮上。但是:

<body>
    <button class="btn-roll">click on me</button>

    <script>
        document.querySelector('.btn-roll').addEventListener('click', myFunction);

        function myFunction(){
            alert(1);
        }
    </script>
</body>

会很好的。
您可以使用jQuery之类的库来确保DOM已准备就绪,如下所示:

<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>

    <script>
        $(document).ready(function(){
            document.querySelector('.btn-roll').addEventListener('click', myFunction);

            // or:
            // $('.btn-roll').on('click',myFunction);

        })


        function myFunction(){
            alert(1);
        }
    </script>

    <button class="btn-roll">click on me</button>

</body>