我正在创建一个这样的秒表:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css?family=Saira" rel="stylesheet">
<link href="stopwatch.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
</head>
<body>
<div class="but">
<h1>Stopwatch</h1>
<p id="timer">0</p>
<button id="start">Start/Stop</button>
<button id="reset">Reset</button>
<button id="record">Record Time</button>
</div>
</body>
</html>
和javascript:
var timer = document.getElementById("timer");
var sec = 0;
document.getElementById("start").addEventListener("click", counter());
function counter(){
setInterval(time(), 10);
}
function time(){
sec++;
timer.innerHTML = sec;
}
但是,当我点击开始按钮时,它不起作用。任何人都可以解释原因吗?
答案 0 :(得分:2)
在线:
document.getElementById("start").addEventListener("click", counter());
这是错误的,它应该是:
document.getElementById("start").addEventListener("click", counter);
当您使用()
时,它正在调用该函数。在这里,您将函数传递给addEventListener
,而不是调用它。
与该行相同:
setInterval(time(), 10);
它应该是:
setInterval(time, 10);
所以你的代码应该是:
var timer = document.getElementById("timer");
var sec = 0;
document.getElementById("start").addEventListener("click", counter);
function counter(){
setInterval(time, 10);
}
function time(){
sec++;
timer.innerHTML = sec;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css?family=Saira" rel="stylesheet">
<link href="stopwatch.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
</head>
<body>
<div class="but">
<h1>Stopwatch</h1>
<p id="timer">0</p>
<button id="start">Start/Stop</button>
<button id="reset">Reset</button>
<button id="record">Record Time</button>
</div>
</body>
</html>
答案 1 :(得分:1)
您必须传递该功能,而不立即调用 :
将document.getElementById("start").addEventListener("click", counter());
更改为document.getElementById("start").addEventListener("click", counter);
将setInterval(time(), 10);
更改为setInterval(time, 10);
见下面的演示:
var timer = document.getElementById("timer");
var sec = 0;
document.getElementById("start").addEventListener("click", counter);
function counter(){
setInterval(time, 10);
}
function time(){
sec++;
timer.innerHTML = sec;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css?family=Saira" rel="stylesheet">
<link href="stopwatch.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
</head>
<body>
<div class="but">
<h1>Stopwatch</h1>
<p id="timer">0</p>
<button id="start">Start/Stop</button>
<button id="reset">Reset</button>
<button id="record">Record Time</button>
</div>
</body>
</html>