我不太擅长 JS,出于某种原因,当我尝试将两个字段加在一起时,它会将它们连接起来而不是将总和加在一起。这是我正在尝试使用的代码。
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
totalVal 正在回显/警告 68.50378.00 而不是将它们相加。有人可以告诉我哪里出错了吗? :( 我的想法是用 totalVal 更新“总计”文本字段,但我还没有做到这一点!
最佳答案
您需要在添加之前将您的值转换为 float :
var totalVal = parseFloat(postage) + parseFloat(subtotal);
编辑:这是一个完整的示例,其中包括对 NaN 的检查:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var postageAsFloat = isNaN(postage) ? 0.0 : postage;
var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
var totalVal = postageAsFloat + subtotalAsFloat;
alert(postage);
alert(subtotal);
alert(totalVal);
};
关于javascript - 简单的 JavaScript 添加问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/955509/