[英]Create Reset button for a counter
I have this counter.我有这个柜台。 It is a counter that uses Javascript Closure.这是一个使用 Javascript Closure 的计数器。 Can you help me with a reset button?你能帮我一个重置按钮吗? If you can, to this type of "counter" code, not to another...如果可以的话,对这种类型的“计数器”代码,而不是对另一个......
HTML CODE HTML 代码
<button type="button" onclick="geo()">Count!</button>
<p id="count">0</p>
JAVASCRIPT CODE JAVASCRIPT 代码
<script>
var count= (function () {
var nr = 0;
return function () {nr+= 1; return nr;}
})();
function geo(){
document.getElementById("count").innerHTML = count();
}
</script>
I'm not even sure what you have right now is working.我什至不确定你现在拥有的东西是否有效。
const addBtn = document.querySelector('#add'); const resetBtn = document.querySelector('#reset'); const pCount = document.querySelector('#count') let start = 0; function add(){ start++ pCount.innerHTML = start } function reset(){ start = 0; pCount.innerHTML = start } addBtn.addEventListener('click', add) resetBtn.addEventListener('click', reset)
<button id="add"> Add </button> <button id="reset" > Reset </button> <p id="count"></p>
I don't know much about the closure (seems very interesting...) but moving nr variable outside of your function and then call a reset on nr will reset the counter.我对关闭不太了解(似乎很有趣......)但是将 nr 变量移到 function 之外,然后在 nr 上调用重置将重置计数器。
var count = (function() { var nr = 0; return function(reset = false) { nr = reset? 0: nr + 1 return nr; } })(); function geo() { document.getElementById("count").innerHTML = count(); } function reset() { document.getElementById("count").innerHTML = count(true); }
<button type="button" onclick="geo()">Count!</button> <button type="button" onclick="reset()">Reset!</button> <p id="count">0</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.