将功能链接到按钮的Javascript

时间:2018-09-15 07:44:33

标签: javascript html button

我将通过单击按钮来调用计时器。 计时器功能

function countDown(seconds, elem){
    var element = document.getElementById(elem);
    element.innerHTML = "Please wait for "+seconds+ " seconds";

    if(seconds < 1){
        clearTimeout(timer);
        element.innerHTML ='<h2> You can let Go, Frist Responders have been informed</h2>';
    }
    seconds--;

    var timer = setTimeout('countDown('+seconds+',"'+elem+'")',1000); 
}

函数调用:

document.querySelector('body').onClick = countDown(5,"para");

HTML:

<div class="wrapper" id="butt2">
<button id="butt" class="fade-in-fwd" >SOS</button>
</div>

<p id="para"></p>

这会在网页加载后立即开始运行计时器。如何限制

1 个答案:

答案 0 :(得分:3)

您的代码中有几个问题:

  1. onClick应写为onclick
  2. onclick需要点击时触发的功能。由于您已在countDown(5,"para")中分配了onclick,因此会立即调用它。

document.querySelector('body').onclick = function(){
  countDown(5,"para");
}
function countDown(seconds, elem) {
  var element = document.getElementById(elem);
  element.innerHTML = "Please wait for " + seconds + " seconds";

  if (seconds < 1) {
    clearTimeout(timer);
    element.innerHTML = '<h2> You can let Go, Frist Responders have been informed</h2>';
  }
  seconds--;

  var timer = setTimeout('countDown(' + seconds + ',"' + elem + '")', 1000);
}
<div class="wrapper" id="butt2">
  <button id="butt" class="fade-in-fwd">SOS</button>
</div>

<p id="para"></p>

  

请注意,如果您在多次初始化计时器而未清除前一个计时器的情况下单击多次,则此代码将出现怪异的行为。