如何在单击时增加计数器

How to increment a counter on click?

本文关键字:增加 计数器 单击      更新时间:2023-09-26

我有以下HTML:

<button id="ES" class="select" type="button">Select</button>
<h2>Total Units: <span id="totalselected"></span></h2>

和脚本:

var units=0;
document.getElementById('ES').onclick = function() {
    var units=units+2;
    document.getElementById("totalselected").innerHTML = units;
}​;​

我希望当按钮被点击时,将+ 2添加到计数器。
它从0开始,并显示在网页上。

点击按钮后,数字跳转到2。
如果再次单击,数字将跳转到4。

删除units上的第二个var

var units=0;
    document.getElementById('ES').onclick = function() {
    units=units+2; // here
    document.getElementById("totalselected").innerHTML = units;
};
演示

改变这个:

var units=units+2;

:

units=units+2;  // remove the keyword var

根据你的帖子:

我想当按钮被点击时,添加+ 2到计数器。它从0开始,并显示在网页上。

0开始你的值,你可以移动你的var unit = unit + 2在底部:

var units=0;
document.getElementById('ES').onclick = function() {
   document.getElementById("totalselected").innerHTML = units;
   units=units+2;
};
<html>
<head>
<script>
 var c=0;
function test()
{
c=c+2;
document.getElementById("cnt").innerHTML=c;
}
</script>
</head>
<body>
<input type="button" value="Click" onClick="test()"/>
Count= <p id="cnt""></p>
</body>
</html>