我有一个带有 javascript 变量和一个按钮的脚本,现在每次我按下这个按钮时,我都希望变量增加一个,我已经尝试过,正如您在下面的脚本中看到的那样,但是存在一些问题,数字不显示,每次单击按钮时数字都不会加一,这是怎么回事?
javascript:
var nativeNR = 1;
function addOne() {
nativeNR = nativeNR + 1;
}
html:
<form id="form">
<input style="width: 500px;" type="add" id="plusButton" onclick="addOne();" />
</form>
current amount <span id="nativeNR"></span>
最佳答案
在您的情况下,每次单击时数字都会增加 1。但是,您没有在跨度中显示它。为此,您可以引用该元素并为其设置 nativeNR。
你的方法应该是这样的
var nativeNR = 1;
function addOne() {
nativeNR = nativeNR + 1;
document.getElementById("nativeNR").innerHTML = nativeNR;
}
<form id="form">
<input style="width: 500px;" type="button" id="plusButton" onclick="addOne();" />
</form>
也没有输入 type="add"
应该是 type="button"
var nativeNR = 1;
document.getElementById("nativeNR").innerHTML = nativeNR
function addOne() {
nativeNR = nativeNR + 1;
document.getElementById("nativeNR").innerHTML = nativeNR;
}
<form id="form">
<input style="width: 500px;" type="button" id="plusButton" value="add" onclick="addOne();" />
</form>
current amount <span id="nativeNR"></span>
关于javascript - 使用按钮添加到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110088/