这个简单的Javascript计算器的哪一部分是错误的?

时间:2014-11-19 19:45:44

标签: javascript

我最近写了这个简单的javascript计算器,但它不起作用,有什么想法吗?



function calculateMe() {
   var x = document.getElementById("x"); 
   var y = document.getElementById("y"); 
   var e = x + y;
   document.getElementById("a").innerHTML = e;
    
}

<center><input id="x"></input> +
<input id="y"></input><br><br>
    <button onclick="calculateMe()">Submit</button><br><br>
        <input id="a"></input>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您需要先从输入中获取值,然后将值设置为:

function calculateMe() {
    var x = +document.getElementById("x").value;
    var y = +document.getElementById("y").value;
    var e = x + y;
    document.getElementById("a").value = e;
}
    <input id="x"></input>+
    <input id="y"></input>
    <br>
    <br>
    <button onclick="calculateMe()">Submit</button>
    <br>
    <br>
    <input id="a"></input>

document.getElementById代码中的+会将您获得的字符串转换为数字。

答案 1 :(得分:0)

<html>
    <head>
        <script>
        function calculateMe() {
            var x = parseInt(document.getElementById("x").value); 
            if(isNaN(x)){
                x = 0;
                document.getElementById("x").value=x;
                alert("The value in the first text box is not a valid number.");
            }
            var y = parseInt(document.getElementById("y").value);
            if(isNaN(y)){
                y = 0;
                document.getElementById("y").value=y;
                alert("The value in the second text box is not a valid number.");
            }           
            var e = x + y;
            document.getElementById("a").value = e;
        }
        </script>
        <title>Webpage</title>
    </head>
    <body>
        <center>
            <input id="x" type="text"> +
            <input id="y" type="text"><br><br>
            <button onclick="calculateMe()">Submit</button><br><br>
            <input id="a" type="text" readonly>
        </center>
    </body>
</html>