为什么这个简单的HTML / JavaScript计算器不起作用?

时间:2016-01-29 15:50:28

标签: javascript html function calculator

这是我的代码:



<!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>
&#13;
&#13;
&#13;

&#34;乘法&#34;按钮返回&#34; NaN&#34;错误和添加按钮始终返回&#34; [objectHTMLInputElement] [objectHTMLInputElement]&#34;

为什么这不起作用?

2 个答案:

答案 0 :(得分:2)

你没有得到价值,只有元素:

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

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

您可能希望从以下内容开始:

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

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

答案 1 :(得分:0)

  1. .value - &gt;你不想要输入元素,你想要它所拥有的值

  2. parseInt - &gt;你想要数字不是字符串(或者如果你想要浮点数,可以是parseFloat)

    function add() {
      var num1 = parseInt(document.getElementById("number1").value);
      var num2 = parseInt(document.getElementById("number2").value);
      var answer = num1 + num2;
      document.getElementById("Answer").innerHTML = answer;
    }
    
    function multiply() {
      var num1 = parseInt(document.getElementById("number1").value);
      var num2 = parseInt(document.getElementById("number2").value);
      var answer = num1 * num2;
      document.getElementById("Answer").innerHTML = answer;
    }