我有两个按钮(+ 和 -)和一个值为 10 的输入框。输入必须仅采用 0 到 10 之间的值,我不明白为什么在达到任一值后我变得未定义输入框上的 0 或 10。我尝试使用 parseInt 作为值。但也许我没有在正确的地方做这件事。非常感谢您的帮助。
var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;
fighter1Inc.onclick = function (valor) {
fighterScore1.value = increaseValue(valor);
};
fighter1Dec.onclick = function (valor) {
fighterScore1.value = decreaseValue(valor.value);
};
function decreaseValue() {
if (valor <= 0 ) {
} else {
valor--;
return valor;
}
};
function increaseValue() {
if (valor >= 10 ) {
valor = 10;
} else {
valor++;
valor = valor;
return valor;
}
};
<div id="rwid1">
<button id="fighter1Inc">+</button>
<input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
<button id="fighter1Dec">-</button>
</div><!--/rwid-->
最佳答案
问题是你只在小于 10 或大于 0 的条件下返回。如果你不在一个条件下返回,则没有返回值,所以你最终会分配 undefined
到一个变量。 Here是一个固定的 JSFiddle。您必须在 if 语句之外返回,并且 valor.value
不存在。
var fighterScore1 = document.getElementById("fighterScore1");
fighterScore1.value = 10;
var fighter1Inc = document.getElementById("fighter1Inc");
var valor = 10;
fighter1Inc.onclick = function (valor) {
fighterScore1.value = increaseValue();
};
fighter1Dec.onclick = function (valor) {
fighterScore1.value = decreaseValue();
};
function decreaseValue() {
if (valor <= 0 ) {
valor = 0;
} else {
valor--;
}
return valor;
};
function increaseValue() {
if (valor >= 10 ) {
valor = 10;
} else {
valor++;
}
return valor;
};
<div id="rwid1">
<button id="fighter1Inc">+</button>
<input type="text" id="fighterScore1" maxlength="10" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
<button id="fighter1Dec">-</button>
</div><!--/rwid-->
注意:您将参数传递给一个不接受任何参数的函数(JS 接受不同数量的参数,即使您没有指定)。要么删除带参数的调用,要么使用参数并将其传入,使用参数代替 valor
。
关于Javascript:输入框未定义,范围为 0 到 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197632/