gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:21:43 25 4
gpt4 key购买 nike

我正在尝试制作一个在单击时将计数器的值增加 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>

最佳答案

你不需要#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>

关于javascript - 如何创建一个在单击时增加计数器的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62189176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com