使用java脚本添加两个数字时我在做什么错误

时间:2016-09-29 14:04:37

标签: javascript html javascript-events

我尝试通过从文本框中获取值来添​​加两个数字然后计算然后使用innerhtml显示它但是它不会在我的代码中执行什么错误



<body onload="alert('Hey check out my Calculator')">
 <h1 align="center" >  functional calulator </h1>
 <div class="Calculator" align="center">
 	<input type="text" name="text1" id="a1">Enter 1st Number <br><br>
 	<input type="text" name="text2" id="a2">Enter 2nd Number<br><br>
 	<button   onclick="add()" >Add</button>
 	<p id="p1"></p>
 	
	<script type="text/javascript">	
		function add(){
			var a = document.getElementById("a1").value;
			var b = document.getElementByID("a2").value;
			var total = a + b;
			document.getElementById("p1").innerHTML = total;
			
			

		}
		</script>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

你是将它们作为一个字符串添加,以便它们被连接起来你应该先将它们解析为整数

var a = parseInt(document.getElementById("a1").value);
var b = parseInt(document.getElementById("a2").value);
var total = a + b;
document.getElementById("p1").innerHTML = total;

答案 1 :(得分:1)

a,b是字符串。也许你想要将它们解析为整数?

答案 2 :(得分:0)

getElementByID应该是getElementById

中的var b = document.getElementById("a2").value;

并为您的a和b执行parseInt()将其视为数字。

&#13;
&#13;
<body onload="alert('Hey check out my Calculator')">
  <h1 align="center">  functional calulator </h1>
  <div class="Calculator" align="center">
    <input type="text" name="text1" id="a1">Enter 1st Number
    <br>
    <br>
    <input type="text" name="text2" id="a2">Enter 2nd Number
    <br>
    <br>
    <button onclick="add()">Add</button>
    <p id="p1"></p>

    <script type="text/javascript">
      function add() {
        var a = document.getElementById("a1").value;
        var b = document.getElementById("a2").value;
        var total = parseInt(a) + parseInt(b);
        document.getElementById("p1").innerHTML = total;
      }
    </script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个 - 你犯了拼写错误 - 它的document.getElementById不是document.getElementByID

&#13;
&#13;
<body onload="alert('Hey check out my Calculator')">
 <h1 align="center" >  functional calulator </h1>
 <div class="Calculator" align="center">
 	<input type="text" name="text1" id="a1">Enter 1st Number <br><br>
 	<input type="text" name="text2" id="a2">Enter 2nd Number<br><br>
 	<button   onclick="add()" >Add</button>
 	<p id="p1"></p>
 	
	<script type="text/javascript">	
		function add(){
           var a = document.getElementById("a1").value;
			var b = document.getElementById("a2").value;
            
			var total = parseInt(a) + parseInt(b);
			document.getElementById("p1").innerHTML = total;
			
			

		}
		</script>
&#13;
&#13;
&#13;