如何使用javascript在h2标签中显示最终结果

时间:2013-09-22 08:11:38

标签: javascript

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

2 个答案:

答案 0 :(得分: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>

请参阅DEMO

答案 1 :(得分:1)

只需使用h2标记并使用

将数据放入其中
html tag:
<h2 id='ele'></h2>


javascript:
document.getElementById('ele').innerHTML="the sum is "+sum;