HTML and Javascript (Adding )

HTML and Javascript (Adding )

本文关键字:Adding Javascript and HTML      更新时间:2023-09-26

我正试图通过html和JavaScript编写一个简单的计算器,然而2+2的结果不是4而是22,请帮助我解决这个问题!谢谢!

<html>
<body>
<input type ="text" id ="x">
<p> + </p>
<input type ="text" id ="y"> 
<script>
function adder(a,b){
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
document.getElementById("demo").innerHTML =  x+y;

}
</script>
<button type = "button" onclick = "adder(x,y)"> calculate </button>
<p id = "demo"> </p>
</body>
</html>

你不是在添加数字,而是字符串,这意味着连接。

先转换为数字:

<html>
<body>
<input type ="text" id ="x">
<p> + </p>
<input type ="text" id ="y"> 
<script>
function adder(a,b){
  var x = Number(document.getElementById("x").value);
  var y = Number(document.getElementById("y").value);
  document.getElementById("demo").innerHTML =  x+y;
}
</script>
<button type = "button" onclick = "adder(x,y)"> calculate </button>
<p id = "demo"> </p>
</body>
</html>

注意,如果输入不能转换为数字,则不包括错误处理。

对ASDFGerte的答案稍作补充需要将元素x和y转换为整数因为get element by id返回字符串为此可以使用parseint函数

var x = parseInt(document.getElementById("x").value);
var y = parseInt(document.getElementById("y").value);