我有一个带有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>
答案 0 :(得分:2)
在您的情况下,每次单击时,数字将增加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>
答案 1 :(得分:0)
您必须使用javascript将该数字实际放入DOM中。另外,请确保函数addOne
不在onload
包装器中;它需要在DOM本身中,并在调用它的input
元素之前声明。
该功能如下所示:
var nativeNR = 1;
function addOne() {
nativeNR = nativeNR + 1;
document.getElementById('nativeNR').innerHTML = nativeNR;
}
这里是JSFiddle
答案 2 :(得分:0)
您还需要将数字写入范围,现在只需将其添加到内存中的变量:
document.getElementById('nativeNR').innerHTML = nativeNR;
此外,您可能希望将输入类型更改为&#34;按钮&#34;。