2012-04-18 36 views
2

我有一个应该保持运行总数的变量。在这个循环的每个过程中,数量应该被添加到运行总数。我必须错过一些东西,因为我得到了undefined或NaN。将数字添加到jquery循环中的运行总数

$('#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); 
})​ 

回答

7

您需要的值初始化为0:

var totalSqft = 0; 

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

+0

与字符串相同,以防某人不知道 – ajax333221 2012-04-18 00:43:49

相关问题