Javascript - 从输入返回连接而不是变量总和

标签 javascript jquery each

我正在尝试使用 .each() 从输入字段中获取值,并将它们相加以在另一个输入值中显示总和。但不幸的是,尽管使用了 parseInt() 我还是无法得到总和。

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>  

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo

最佳答案

你正在解析的行是在说

Add the totalValue to the string from the input, then parse the result.

这就是它串联的原因。相反,您需要添加 parseInt()totalValue outside 以便它说

Take the take the totalValue and add the parsed input value to it.

像这样

totalvalue = totalvalue + parseInt($(this).val());

这可以进一步缩短为

totalvalue += parseInt($(this).val());

关于Javascript - 从输入返回连接而不是变量总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44940503/

相关文章:

javascript - 计算 fitBounds() 为给定边界和 map 大小返回的视口(viewport)

JavaScript 游戏敌人继承 - Phaser 框架

javascript - 如何在考虑缓存的情况下延迟加载 iframe

jquery - 重定向代码不起作用

javascript - Jquery each 方法

javascript - 如何减少使用 JQuery 和 .each() 的 javascript 代码

java - 正确格式化 Java 字符串以适应 JavaScript 变量

javascript - 将 AngularJS $filter 与 ng-disabled 一起使用

jquery - 2 列主体,可变宽度,100% 高度,固定页眉和页脚

jquery - 是否可以使用 .each 让 .animate 对每个元素起作用?