如何求和2个数字

我需要对两个数字求和,但它给了我 NaN。我怎样才能让它工作?我已经尝试过 parseInt 但同样的事情。


<!DOCTYPE html>

<html>

<head>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width">

  <title>JS Bin</title>

</head>

<body>

  <p id="num1">5</p>

  <p id="num2">5</p>

  <p id="res">1</p>

</body>

<script>

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

  var num2 = document.getElementById("num2").value;

  var res = num1 + num2;

  document.getElementById("res").innerHTML = res;

</script>

</html>


牧羊人nacy
浏览 181回答 3
3回答

ITMISS

<!DOCTYPE html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset="utf-8">&nbsp; &nbsp; &nbsp; &nbsp; <meta name="viewport" content="width=device-width">&nbsp; &nbsp; &nbsp; &nbsp; <title>JS Bin</title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <p id="num1">5</p>&nbsp; &nbsp; &nbsp; &nbsp; <p id="num2">5</p>&nbsp; &nbsp; &nbsp; &nbsp; <p id="res">1</p>&nbsp; &nbsp; &nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var num1 = document.getElementById("num1").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var num2 = document.getElementById("num2").innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var res = parseInt(num1) + parseInt(num2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("res").innerHTML = res;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; </script>&nbsp; &nbsp; </body></html>

开心每一天1111

您应该使用 Number(document.getElementById("num1").innerText),因为 p 标签的 value 属性不存在。

小怪兽爱吃肉

您已使用“值”而不是innerHTML 来获取数字。<!DOCTYPE html><html><head>&nbsp; <meta charset="utf-8">&nbsp; <meta name="viewport" content="width=device-width">&nbsp; <title>JS Bin</title></head><body>&nbsp; <p id="num1">5</p>&nbsp; <p id="num2">5</p>&nbsp; <p id="res">1</p></body><script>&nbsp; var num1 = parseInt(document.getElementById("num1").innerHTML);&nbsp; var num2 = parseInt(document.getElementById("num2").innerHTML);&nbsp; var res = num1 + num2;&nbsp; document.getElementById("res").innerHTML = res;</script></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript