JavaScript计算加法值

时间:2015-01-27 15:58:20

标签: javascript html

我无法从输入中添加2个数字。

<script> 
x = document.getElementById('input1').value;
y = document.getElementById('input2').value;
z = Number(x)+ Number(y);
document.getElementById('submit1').addEventListener("click",alpha);
function alpha(){document.getElementById('div1').innerHTML="The answer is" + z;}
</script> 

我只需要在javaSCript的帮助下完成这项工作。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

document.getElementById('submit1').addEventListener("click", function(){

    // I suppose that the values you insert in your inputs are 
    // integers. Otherwise, you could use the parseFloat(value, 10)
    // to parse float =s.
    var x = parseInt(document.getElementById('input1').value);
    var y = parseInt(document.getElementById('input2').value);

    // Add the numbers
    var z = x + y;

    // Set the result in the selected div.
    document.getElementById('div1').innerHTML="The answer is" + z;
});

您可以尝试运行以下代码段:

document.getElementById('submit1').addEventListener("click", function(){

    // I suppose that the values you insert in your inputs are 
    // integers. Otherwise, you could use the parseFloat(value, 10)
    // to parse float =s.
    var x = parseInt(document.getElementById('input1').value);
    var y = parseInt(document.getElementById('input2').value);

    // Add the numbers
    var z = x + y;

    // Set the result in the selected div.
    document.getElementById('div1').innerHTML="The answer is " + z;
});
<input type="text" id="input1"/>
<br/>
<input type="text" id="input2"/>
<br/>
<div id="div1">
</div>
<br/>
<button id="submit1">submit</button>

答案 1 :(得分:-1)

您想使用parseInt()将字符串转换为int。

   <html>
    <head>
    <title></title>
    <style>
    </style>
    <script>
        document.addEventListener("DOMContentLoaded", function(){
            document.getElementById("button").addEventListener("click",function(){
                var a = parseInt(document.getElementById("input1").value);
                var b = parseInt(document.getElementById("input2").value);
                document.getElementById("output").innerHTML="The Answer is "+(a+b);
            },false);
        });
    </script>
    </head>
    <body>
        <input id="input1" type="text"/>
        <input id="input2" type="text"/>
        <button id="button">Add</button>
        <div id="output"></div>
    </body>
    </html>