在这里,sums [i] .value得到了正确的值,但是当我想保留所有Sum的总和时,它就失败了。
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
答案 0 :(得分:1)
纯HTML是字符串,一直向下,var amounts = document.getElementsByName("Amount");
后跟amounts.value
表示您现在有字符串值。由于+
也是一个字符串运算符,JavaScript很乐意将"2"+"4"
转换为“24”,这看起来像数学一样,但是错误的,实际上它根本就没有数学运算。
首先将所有需要数字的值转换为数字:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
答案 1 :(得分:0)
用以下代码替换您的代码:
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
答案 2 :(得分:0)
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
这应该对你有帮助。
答案 3 :(得分:0)
添加和乘以
时删除.valuefunction test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}