我将通过单击按钮来调用计时器。 计时器功能
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>
这会在网页加载后立即开始运行计时器。如何限制
答案 0 :(得分:3)
您的代码中有几个问题:
onClick
应写为onclick
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>
请注意,如果您在多次初始化计时器而未清除前一个计时器的情况下单击多次,则此代码将出现怪异的行为。