Javascript 如何对输入标签中的两个数字求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11961474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:51:00  来源:igfitidea点击:

how to sum two numbers from input tag?

javascriptinputtags

提问by user1599289

Possible Duplicate:
How to add two strings as if they were numbers?

可能的重复:
如何将两个字符串相加,就好像它们是数字一样?

I wrote a simple JavaScript code and I want to use two input box and add numbers from the two value. Here's the code, and I see the result 1520 instead of 35.

我写了一个简单的 JavaScript 代码,我想使用两个输入框并从两个值中添加数字。这是代码,我看到结果是 1520 而不是 35。

How can I fix it?

我该如何解决?

n1 <input type = "number" id = "n1" value=15 />
n2 <input type = "number" id = "n2" value=20 />

<p>Sum?</p>
<button onclick="sum()">Try it</button>
<p id="demo2">Result?? </p>

<script type="text/javascript">
 function sum() 
{ 
    var fn, ln; 
    fn = document.getElementById("n1").value; 
    ln = document.getElementById("n2").value; 
    result =  (fn+ln); 
    document.getElementById("demo2").innerHTML = result; 
}
</script>

回答by David says reinstate Monica

Use parseInt(), or parseFloat(); the problem you were experiencing is that you were concatenating two strings, not adding two numbers. parseInt()(assuming that it finds a real number) addresses that issue by converting the string to a number:

使用parseInt(), 或parseFloat(); 您遇到的问题是您正在连接两个字符串,而不是将两个数字相加。parseInt()(假设它找到一个实数)通过将字符串转换为数字来解决该问题:

 function sum() 
{ 
    var fn, ln, result; 
    fn = parseInt(document.getElementById("n1").value, 10);
    ln = parseInt(document.getElementById("n2").value, 10);
    result =  (fn+ln); 
    document.getElementById("demo2").innerHTML = result; 
}

The , 10that appears after the valueis the radix, which ensures which number-base the returned number (if any) will be.

, 10那之后的出现value是基数,这确保其中数个碱基返回的数字(如果有的话)会。

Also note that the resultvariable should be declared within the function as well, to avoid polluting the global scope (and possibly creating problems with other variables elsewhere).

另请注意,该result变量也应在函数内声明,以避免污染全局范围(并可能在其他地方与其他变量产生问题)。

References:

参考:

回答by KingKongFrog

result =  (parseFloat(fn)+parseFloat(ln));