0

我需要一点 JavaScript 数学方面的帮助。我想在 h2 标记中显示最终结果,但我不知道该怎么做(我是 JavaScript 新手)。请提前帮助和感谢。

<!doctype html>
<html>
<head>
<title>Do Math</title>
</head>
<body>
    <input type = "number" id = "my_input1"/>
    <input type = "number" id = "my_input2"/>
    <input type = "button" value = "Add them Together" onclick = "doMath();"/>
    <script type = "text/javascript">
        function doMath() {
            var my_input1 = document.getElementById('my_input1').value;
            var my_input2 = document.getElementById('my_input2').value;
            //Add them Together and Display

            var sum = parseFloat(my_input1) + parseFloat(my_input2);
            document.write("<h2>The sum is </h2>", sum);
        }
    </script>
</body>
</html>
4

2 回答 2

1

只需使用一个 h2 标签并将数据放入其中

html tag:
<h2 id='ele'></h2>


javascript:
document.getElementById('ele').innerHTML="the sum is "+sum;
于 2013-09-22T08:25:18.047 回答
1

尝试这个

<html>
    <head>
      <title>Do Math</title> 
    </head>
    <body>
      <input type = "number" id = "my_input1"/>
      <input type = "number" id = "my_input2"/>
      <input type = "button" value = "Add them Together" onclick = "doMath();"/>
      <h2 id="output"></h2>
      <script type = "text/javascript">
              function doMath() {
                  var my_input1 = document.getElementById('my_input1').value;
                  var my_input2 = document.getElementById('my_input2').value;
                  //Add them Together and Display

                  var sum = parseFloat(my_input1) + parseFloat(my_input2);
                  document.getElementById('output').innerHTML = "The sum is " +  sum;
               }
       </script>
    </body>
   </html>

演示

于 2013-09-22T08:20:04.920 回答