我正在尝试创建一个按钮,单击该按钮将启动计时器,第二次单击将停止它并将“按钮”的innerHtml更改为停止计时器的时间。然而,它不适用于我在下面编写的代码,Interval只是继续前进,它似乎就像每次点击创建多个代码一样。
任何想法为什么?
var active = false;
var sec = 0;
function clock(){
if(active === false) {
var clock = setInterval("timer()", 1000);
active = true;
}
else if(active === true){
clearInterval(clock);
document.getElementById("button").innerHTML = "You clicked at "+sec+" seconds, try again.";
active = false;
sec = 0;
}
}
function timer() {
sec++;
document.getElementById("button").innerHTML = sec;
}
答案 0 :(得分:2)
每次单击按钮时,var clock;
都没有相同的上下文,下次点击时此变量的最后一个上下文将丢失,因此请将其设为全局,就像使用{{{ 1}}并重命名与您的函数名称不同,以避免麻烦:
<强> JS 强>
var active;
<强> HTML 强>
var active = false;
var sec = 0, clck;
function clock() {
if (active === false) {
clck = setInterval("timer()", 1000);
active = true;
} else if (active === true) {
clearInterval(clck);
document.getElementById("button").innerHTML = "You clicked at " + sec + " seconds, try again.";
active = false;
sec = 0;
}
}
function timer() {
sec++;
document.getElementById("button").innerHTML = sec;
}
答案 1 :(得分:0)
你错过了点击事件处理程序和任何HTML示例,所以我已经实现了缺少的东西,并提出了这个。
<!DOCTYPE html>
<html>
<head>
<script>
var active = true;
var sec = 0;
var timer;
function init() {
var button = document.getElementById("button");
button.addEventListener("click", function() {
active = !active;
if(active) {
clearInterval(timer);
button.innerHTML = "You clicked at " + sec + " seconds, try again!";
sec = 0;
}
else {
timer = setInterval(function() {
sec++;
button.innerHTML = sec;
}, 1000);
}
});
}
</script>
</head>
<body onload="init();">
<span id="button">Start</span>
</body>