在H2标签中显示最终结果

在H2标签中显示最终结果

我需要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>

最佳答案

尝试这个

<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>


DEMO

10-08 11:55