我在验证 JavaScript 的两个条件时遇到问题。当我输入一个数字时,第一个 if
语句将起作用。但是,else if
语句不会打印出符合该条件的任何内容。一些帮助将不胜感激。
<html>
<head>
<script>
function return() {
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var x = num1.value;
var y = num2.value
if (isNaN(x)) {
alert("Please only enter numbers");
return false;
}
if (isNaN(y)) {
alert("Please only enter numbers");
return false;
}
var calculation = (x + y) / (x * y);
var result = document.getElementById("answer");
if (calculation > 1) {
result.value = "Your number is more than 1";
} else {
if (calculation <= 0.5) {
result.value = "Your number is 1 or less";
}
}
}
</script>
</head>
<body>
1: <input type="text" id="num1"/>
2: <input type="text" id="num2"/>
<input type="button" value="Calculate" onclick= "return()"/>
<input type="text" id="answer"/>
</body>
</html>
最佳答案
You can not use reserved words as function names, variable names or labels.
还将输入值转换为Number
,Unary plus
可用于。
InputElement.value
返回 String
类型的值,因此如果值为 2
和 3
,计算将为 ("2"+ "3"==> "23")
,值将被连接,而不是相加!
另请注意,您有一个未处理的缺失条件,您还应该有其他条件。
function calculate() {
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var x = num1.value;
var y = num2.value
if (isNaN(x)) {
alert("Please only enter numbers");
return false;
}
if (isNaN(y)) {
alert("Please only enter numbers");
return false;
}
var calculation = (+x + +y) / (x * y);
var result = document.getElementById("answer");
if (calculation > 1) {
result.value = "Your number is more than 1";
} else {
if (calculation <= 0.50) {
result.value = "Your number is 1 or less";
} else {
result.value = "Unhandled condition!";
}
}
}
1: <input type="text" id="num1" /> 2: <input type="text" id="num2" />
<input type="button" value="Calculate" onclick="calculate()" />
<input type="text" id="answer" />
关于javascript - 用于比较 2 个不同条件下的数字的 If...Else If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751253/