有关简单Javascript / HTML的问题

时间:2019-03-11 23:25:21

标签: javascript html

我一直在自学一些Javascript;而且我无法让此功能正常运行。 这就是输出。

答案:[object HTMLInputElement] [object HTMLInputElement]

function addNumbers() {
  var firstNum = document.getElementById("num1");
  var secondNum = document.getElementById("num2");
  result = firstNum + secondNum;
  document.getElementById("demo").innerHTML = "Answer: " + result;
  return result;

}
<!DOCTYPE html>
<html>

<head>
  <!--            ,<script src="scripts.js"></script> -->
</head>

<body>

  <h2>JavaScript Functions</h2>

  <p>This example calls a function which performs a calculation and returns the result:</p>


  <form>
    First Number<br>
    <input type="text" name="firstNum" id="num1"><br> Second Number<br>
    <input type="text" name="secondNum" id="num2"><br>
    <input type="button" value="Add!" onclick="addNumbers()">
  </form>

  <p id="demo"></p>
</body>

</html>

1 个答案:

答案 0 :(得分:4)

就像评论中所说的,从HTML元素节点获取值并将其解析为浮点数

var firstNum = parseFloat(document.getElementById("num1").value);
var secondNum = parseFloat(document.getElementById("num2").value);

function addNumbers() {
  var firstNum = parseFloat(document.getElementById("num1").value);
  var secondNum = parseFloat(document.getElementById("num2").value);
  result = firstNum + secondNum;
  document.getElementById("demo").innerHTML = "Answer: " + result;
  return result;

}
<!DOCTYPE html>
<html>

<head>
  <!--            ,<script src="scripts.js"></script> -->
</head>

<body>

  <h2>JavaScript Functions</h2>

  <p>This example calls a function which performs a calculation and returns the result:</p>


  <form>
    First Number<br>
    <input type="text" name="firstNum" id="num1"><br> Second Number<br>
    <input type="text" name="secondNum" id="num2"><br>
    <input type="button" value="Add!" onclick="addNumbers()">
  </form>

  <p id="demo"></p>
</body>

</html>