-2

在这里, 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
        }

    }
4

4 回答 4

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
...
于 2013-06-11T12:24:24.870 回答
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
}
于 2013-06-11T12:24:53.710 回答
0
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);

这应该可以帮助你。

于 2013-06-11T12:26:03.323 回答
0

在加法和乘法时删除 .value

function 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
           }
    }
于 2013-06-11T12:46:16.963 回答