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