how to sum two numbers from input tag?(如何将输入标签中的两个数字相加?)
问题描述
可能重复:
如何将两个字符串像数字一样相加?
我写了一个简单的 JavaScript 代码,我想使用两个输入框并从两个值中添加数字.这是代码,我看到的结果是 1520 而不是 35.
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.
我该如何解决?
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>
推荐答案
使用 parseInt()
或 parseFloat()
;您遇到的问题是您连接两个字符串,而不是添加两个数字.parseInt()
(假设它找到一个实数)通过将字符串转换为数字来解决该问题:
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:
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;
}
出现在value
之后的, 10
是基数,它确保返回的数字(如果有的话)是哪个基数.
The , 10
that appears after the value
is the radix, which ensures which number-base the returned number (if any) will be.
还要注意,result
变量也应该在函数中声明,以避免污染全局范围(并可能在其他地方与其他变量产生问题).
Also note that the result
variable should be declared within the function as well, to avoid polluting the global scope (and possibly creating problems with other variables elsewhere).
参考资料:
parseFloat()
一个>.parseInt()
一个>.
这篇关于如何将输入标签中的两个数字相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将输入标签中的两个数字相加?


- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01