2012-04-18 90 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

相關問題