【问题标题】:Adding numbers to running total in jquery loop在jquery循环中将数字添加到运行总数
【发布时间】:2012-04-18 00:25:32
【问题描述】:

我有一个变量应该保存一个运行总计。在此循环的每次传递中,应将金额添加到运行总数中。我必须遗漏一些东西,因为我得到未定义或 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);
})​

【问题讨论】:

    标签: javascript jquery numbers


    【解决方案1】:

    需要将值初始化为0:

    var totalSqft = 0;
    

    否则,它会被初始化为undefined,而undefined + 一个数字是NaN

    【讨论】:

    • 字符串也一样,以防有人不知道
    猜你喜欢
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多