objectHTMLInputElement

objectHTMLInputElement

这是我的代码:



<!DOCTYPE html>
<html>
<header></header>

<body>
  <label id="FirstNumber">First Number:</label>
  <input type="text" id="number1">
  <br>
  <label id="SecondNumber">Second Number:</label>
  <input type="text" id="number2">
  <br>
  <button id="add" onclick="add()">Add</button>
  <button id="multiply" onclick="multiply()">Multiply</button>
  <br>
  <label id="FinalNumberLabel">Answer:</label>
  <label id="Answer"></label>
  <script type="text/javascript">
    function add() {
      var num1 = document.getElementById("number1");
      var num2 = document.getElementById("number2");
      var answer = num1 + num2;
      document.getElementById("Answer").innerHTML = answer;
    }

    function multiply() {
      var num1 = document.getElementById("number1");
      var num2 = document.getElementById("number2");
      var answer = num1 * num2;
      document.getElementById("Answer").innerHTML = answer;
    }
  </script>
</body>

</html>





“乘”按钮返回“ NaN”错误,而“添加”按钮始终返回“ [objectHTMLInputElement] [objectHTMLInputElement]”

为什么不起作用?

最佳答案

您没有得到值,只有元素:

var num1 = document.getElementById("number1");


在这种情况下,num1实际上不是数字,而是一个objectHTMLInputElement

您可能想从以下内容开始:

var num1 = parseFloat(document.getElementById("number1").value);


也许还添加一些错误检查,或指定输入需要为数字等。

09-28 00:27