【问题标题】:How to get the counter to start from 0 again in JavaScript如何让计数器在 JavaScript 中再次从 0 开始
【发布时间】:2021-11-18 18:17:03
【问题描述】:
好的。我正在尝试一个计算onclick数字的功能。有2个按钮;一个计数的和一个保存数字的。单击后者时,前者应从 0 开始计数,但我的代码从当前数字开始
let count = 1;
function increment() {
console.log("The button was clicked");
document.getElementById("count-el").innerText = count;
count += 1;
}
function save() {
document.getElementById("save-btn").innerText = count - 1;
document.getElementById("count-el").innerText = 0;
}
body {
margin: -2px 0 0 0;
zoom: .8;
}
h1, h2 {
margin: 0;
}
<h1>People entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
<button id="save-btn" onclick="save()">SAVE</button>
【问题讨论】:
标签:
javascript
count
increment
【解决方案1】:
当您保存数据时,只需更新您的计数变量..
let count = 1;
function increment() {
console.log("The button was clicked");
document.getElementById("count-el").innerText = count;
count += 1;
}
function save() {
document.getElementById("save-btn").innerText = count - 1;
document.getElementById("count-el").innerText = 0;
count = 1;
}
<h1>People entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
<button id="save-btn" onclick="save()">SAVE</button>
【解决方案2】:
所以,在保存函数中,只需更新您命名为“count”的“let”
function save() {
document.getElementById("save-btn").innerText = count - 1;
document.getElementById("count-el").innerText = 0;
count = 1;
}