[英]Javascript incrementing by more than one
var x1 = document.getElementById("x1"); var x2 = document.getElementById("x2"); function ThisEvent(){// needs a lot of work done to it if (x1.value==1) { x2.value--; } else if (x1.value==2) { x2.value++; } else if (x1.value==3) { x2.value+=5; } }
<input type="text" value="0" id="x1" onblur="ThisEvent()"> x1 </br> <input type="text" value="0" id="x2"> x2
what is happening now is the digit is being added instead of incrementing when 3 is the input if x1. 现在发生的是,如果x1为3,则数字将被添加而不是递增。 how do you make it increment by more than just one, without it being added it as a digit?
如何使它增加一个以上,而又不将其添加为数字?
if (x1.value == 3) {
x2.value = parseInt(x2.value) + 5;
}
It's interpreting it as a string. 它将其解释为字符串。 You can
parseInt
the x2.value
in the calculation. 您可以
parseInt
的x2.value
在计算中。
The value of the input is a String , you need to convert it to a Number in order to perfom an addition on it. 输入的值是String ,您需要将其转换为Number才能在其上进行加法运算。
You could do it like this: 您可以这样做:
function ThisEvent() { // needs a lot of work done to it
var valX1 = Number(x1.value);
var valX2 = Number(x2.value);
if (valX1 == 1) {
valX2--;
} else {
if (valX1 == 2) {
valX2++;
} else {
if (valX1 == 3) {
valX2 += 5;
}
}
}
x2.value = valX2;
}
jsFiddle: https://jsfiddle.net/v1utqv7f/ jsFiddle: https ://jsfiddle.net/v1utqv7f/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.