如何创建一个在单击时增加计数器的按钮?

2023-11-26

我正在尝试制作一个按钮,单击时计数器的值会增加 1。然而,我的代码似乎不起作用。

var count = 1;
var button = document.querySelector("#increment");

button.addEventListener("click", function() {
  var increment = document.getElementById("#count");
  increment.value = count;
  count++;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
  <button id="decrement">Decrement</button>
  <button id="increment">Increment</button>
</div>

你不需要# in getElementById并使用innerHTML设置值。 不要使用querySelector当你可以通过 id 获取时。

像这样:

let count = 0;
const button = document.getElementById("increment");
const button2 = document.getElementById("decrement");
const textHolder = document.getElementById("count");
textHolder.innerHTML = count;

button.addEventListener("click", function() {
  textHolder.innerHTML = ++count;
});

button2.addEventListener("click", function() {
  textHolder.innerHTML = --count;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
  <button id="decrement">Decrement</button>
  <button id="increment">Increment</button>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建一个在单击时增加计数器的按钮? 的相关文章

随机推荐