如何创建一个在单击时增加计数器的按钮? [英] How can I create a button that increments a counter when clicked?
本文介绍了如何创建一个在单击时增加计数器的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个按钮,在单击时将计数器的值增加 1.但是,我的代码似乎不起作用.
var count = 1;var button = document.querySelector("#increment");button.addEventListener("点击", function() {var increment = document.getElementById("#count");增量值 = 计数;计数++;});
<h4>当前计数:<span id="count">0</span></h4><div class="容器"><button id="decrement">Decrement</button><button id="increment">Increment</button>
解决方案
getElementById
中不需要 #
而使用 innerHTML
设定值.可以通过 id 获取时不要使用 querySelector
.
像这样:
let count = 0;const button = document.getElementById("增量");const button2 = document.getElementById("递减");const textHolder = document.getElementById("count");textHolder.innerHTML = 计数;button.addEventListener("点击", function() {textHolder.innerHTML = ++count;});button2.addEventListener("点击", function() {textHolder.innerHTML = --count;});
<h4>当前计数:<span id="count">0</span></h4><div class="容器"><button id="decrement">Decrement</button><button id="increment">Increment</button>
I am trying to make a button that increments a counter's value by 1 when clicked. My code, however, doesn't seem to work.
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>
解决方案
You don't need #
in getElementById
and use innerHTML
to set value.
Don't use querySelector
when you can get by id.
Like this:
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>
这篇关于如何创建一个在单击时增加计数器的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文