每当按下按钮时,我想增加h3标签显示的数字,但似乎找不到解决方案。



var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");

button1.addEventListener("click", () => {
  var num = 0;
  num += 1;
  outPut.innerHTML = num;
})

<h1>Counter</h1>
<div id="display">
  <h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

最佳答案

您在错误的范围内声明了变量(num)。由于您已在函数内部声明了计数器变量(num),因此在每次单击时都会使用初始值0创建该变量。要保留先前的值,请在函数外部声明变量。

另外,如果文本是纯文本(不是htmlString),我建议您使用innerTexttextContent代替innerHTML



var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");
var num = 0;
button1.addEventListener("click", () => {
  num += 1;
  outPut.textContent = num;
})

<h1>Counter</h1>
<div id="display">
  <h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

09-25 17:30