javascript - 使用按钮添加到变量

标签 javascript html variables numbers add

我有一个带有 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/

相关文章:

javascript - 使用 closest 函数查找属性值

javascript - 我收到错误 "return binding.PBKDF2(password, salt, iterations, keylen, callback); ^ TypeError: Not a buffer"

html - 在 TABLE 固定的情况下是否可以保持 TD 的流动性?

c - C 编程中如何调用变量指定 printf 的格式

c# - 从 C# 中的 HTML 响应中解析 javascript 值

java - 在 void 方法中更改变量?

javascript - 如何更改单击时按钮的类别

html - 以缓冲和高效的方式将音频发送到Node Js-也许使用WebRTC

html - 如何使用[位置: fixed ]?设置dom节点的正确宽度

javascript - 如何检测 javascript 中链接的类别?