除非我在这里将值设置为零,否则为什么它显示 NaN?我希望它保持运行总计并只显示占位符,但除非我将输入的值设置为 0,否则它会在显示总计的总计 div 中显示为 NaN?
$("body").on("blur", "#serviceContract,#gapInsurance,#extendedWarranty,#amtOwedOnTrade,#tradeInValue,#manufacturerRebate,#downPayment,#estimatedTaxesAndFees,#vehiclePrice",function() {
updateTotal();
});
var updateTotal = function() {
var input1 = parseInt($('#vehiclePrice').val());
var input2 = parseInt($('#estimatedTaxesAndFees').val());
var input3 = parseInt($('#downPayment').val());
var input4 = parseInt($('#manufacturerRebate').val());
var input5 = parseInt($('#tradeInValue').val());
var input6 = parseInt($('#amtOwedOnTrade').val());
var input7 = parseInt($('#extendedWarranty').val());
var input8 = parseInt($('#gapInsurance').val());
var input9 = parseInt($('#serviceContract').val());
if (input1 ==undefined || input2 == undefined || input3 == undefined || input4 == undefined || input5 == undefined || input6 == undefined || input7 == undefined || input8 == undefined ||input9 == undefined ) {
$('#total').text(total);
} else {
var max = 40000;
var total = input1 + input2 - input3 - input4 - input5 + input6 + input7 + input8 + input9;
if (total > max) {
$('#total').text('The maximum is ' + max);
$('#total1').val(40000);
} else {
$('#total').text(total);
$('#total1').val(total);
}
}
};
最佳答案
因为当字段为空时,它不会解析任何内容,返回NaN。
您可以通过在每一行上执行此操作来防止这种情况:
var input1 = parseInt($('#vehiclePrice').val()) || 0;
如果 val 为“假”,则计算结果为 0。
<小时/>正如 CodeMoose 所说:
“使用 parseInt 时始终定义以 10 为基数:parseInt($('#vehiclePrice').val(), 10)
。”
该参数是基数
radix
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
取自 MDN
关于javascript - 始终显示总计并停止显示 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21266026/