使用按钮添加到变量

Add to variable with a button

本文关键字:变量 添加 按钮      更新时间:2023-09-26

我有一个脚本,里面有一个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>

在您的情况下,每次单击都会增加一个数字。但是,您不会在跨度中显示它。因此,要做到这一点,您可以引用元素并将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将该数字实际放入DOM中。此外,请确保函数addOne不在onload包装器中;它需要在DOM本身中,并在调用它的input元素之前声明。

功能如下:

var nativeNR = 1;
function addOne() {
    nativeNR = nativeNR + 1;
    document.getElementById('nativeNR').innerHTML = nativeNR;
}

这是一个JSFiddle

您还需要将数字写入span,现在您只需将其添加到内存中的变量:

document.getElementById('nativeNR').innerHTML = nativeNR;

此外,您可能希望将输入类型更改为"按钮"。