问题描述
页面上有一个按钮,点击按钮开始计时,页面上显示经过了多少时间,再次点击计时停止。
页面显示如下:
<html>
<head>
</head>
<body>
<button id="start">Start</button>
<p><span id="counter">0</span> elapsed second(s)</p>
</body>
</html>
解决办法
我的:
//Write-Your-Code-Here
const counterElement = document.getElementById("counter");
const buttonElement = document.getElementById("start");
let intervalId;
const addSeconds = () =>
{
const counter = Number(counterElement.textContent);
counterElement.textContent = counter + 1;
};
buttonElement.addEventListener("click",e =>{
if(buttonElement.textContent === "Start")
{
intervalId = setInterval(addSeconds, 1000);
buttonElement.textContent = "Stop";
}
else
{
clearInterval(intervalId);
buttonElement.textContent = "Start";
}
});
参考答案:
const buttonElement = document.querySelector("button");
const counterElement = document.getElementById("counter");
// Global variable to access it from function
let intervalId = null;
// Chronometer state, initially stopped
let started = false;
buttonElement.addEventListener("click", () => {
if (!started) {
// Start the chronometer: add 1 to the counter each second
intervalId = setInterval(() => {
counterElement.textContent = String(Number(counterElement.textContent) + 1);
}, 1000);
// Update button text
buttonElement.textContent = "Stop";
} else {
// Stop the chronometer
clearInterval(intervalId);
// Update button text
buttonElement.textContent = "Start";
}
// Change chronometer state
started = !started;
});