javascript - 用于比较 2 个不同条件下的数字的 If...Else If 语句

标签 javascript html

我在验证 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.

还将输入值转换为NumberUnary plus可用于。


InputElement.value 返回 String 类型的值,因此如果值为 23,计算将为 ("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/

相关文章:

php - 使用 PHP 获取图像文件路径并以 HTML 显示

javascript - Angular 1.6 错误 : [$injector:modulerr]

javascript - Promise/bluebird.js 中的错误处理

html - 显示与文本相邻的图像时调整大小问题

html - 悬停时弹出图像CSS链接

jquery - 使标签位置在滚动时固定

css - 我可以使用CSS来颠倒两个元素的显示顺序吗?

javascript - 我应该在 Electron 应用程序中使用视口(viewport)元吗?

javascript - Angular *ngFor 循环遍历数组的数组

javascript - Rails PATCH 方法而不是 POST