javascript - 在 jquery 循环中将数字添加到运行总计中

标签 javascript jquery numbers

我有一个应该保存运行总计的变量。在此循环的每次传递中,金额都应添加到运行总计中。我一定是错过了一些东西,因为我得到的要么是未定义的,要么是 NaN。

$('#btnSubmit').click(function(e) {
    var totalSqft;
    $('.fieldset').each(function() {
        var sqft;
        var width = $(this).find('input:eq(0)').val();
        var height = $(this).find('input:eq(1)').val();
        var type = $(this).find('select').val();
        if (type == 'tri') {
            sqft = (width * height) / 2;
        } else {
            sqft = (width * height);
        };
        totalSqft += sqft;
        alert('this ' + type + ' is ' + width + ' wide and ' + height + ' high, for a total of ' + sqft + ' square feet');
    });
    alert('Done.  Total Sq Ft is ' + totalSqft);
})​

最佳答案

您需要将值初始化为0:

var totalSqft = 0;

否则,它会被初始化为未定义,并且未定义 + 数字为NaN

关于javascript - 在 jquery 循环中将数字添加到运行总计中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201096/

相关文章:

python - 在python中生成1到6之间的6个随机数列表

javascript - 如何根据访客推荐使用 Javascript(或 PHP)将值插入到表单中

javascript - 如何让导航栏下拉菜单与主体重叠?

javascript - 我可以使用 JavaScript 代替 PHP,用 Node.js 代替 Apache 吗?

jquery - 如何重新加载嵌入html页面的pdf

javascript - 双数范围验证的正则表达式

javascript - Meteor 包中 api.add_files 缺少文件

javascript - 当您访问其中包含特定 ID 的 URL 时添加 CSS

javascript - 如何在将 <li> 附加到 <li> 组中时滚动 <li>

c++ - 检查完美数字的程序 - 出了点问题