0

我有一张表,想计算每个元素,如:

calc-this-cost * calc-this-cost(value of checkbox) = calc-this-total

然后将所有calc-this-cost内容相加并将其放入totalcost div。这是表:

  <td class="params2">
    <table id="calc-params">
    <tr>
    <td>aaa</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
    <input type="checkbox" name="a002" value="0" onclick="calculate(this);" />
    </td><td class="calc-this-total">0</td>
    </tr>
    <tr>
    <td>bbb</td><td class="calc-this-cost">230073</td><td class="calc-this-count">
    <input type="checkbox" name="a003" value="0" onclick="calculate(this);" />
    </td><td class="calc-this-total">0</td>
    </tr>
    <tr>
    <td>ccc</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
    <input type="checkbox" name="a004" value="1" onclick="calculate(this);" />
    </td><td class="calc-this-total">0</td>
    </tr>
    ........
    </table>
    .......
    </td>
<div id="calc-total-price">TOTAL COST:&nbsp;&nbsp;<span>0</span></div>

我的脚本(在函数计算中)

var totalcost=0;
    $('.params2 tr').each(function(){
        var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
        var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
        $('.calc-this-total',$(this)).html(count*price);
        totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
    });
    $('#calc-total-price span').html(totalcost);

计算每个元素并将结果放入 calc-this-cost - 完美运行。

但总成本结果为 NaN。为什么?

4

2 回答 2

2
  1. [一般] parseFloat() 不要超过你需要的
  2. [general] 将重复代码移动到函数中
  3. [jQuery] 在上下文和缓存节点上使用 .find() ($row)
  4. [通用] 看看 String.replace() 是如何工作的
  5. [general] 查看 Number.toFixed() 以显示浮点数

例子

var totalcost = 0,
    toFloat = function(value) {
        // remove all whitespace
        // note that replace(" ", '') only replaces the first _space_ found!
        value = (value + "").replace(/\s+/g, '');
        value = parseFloat(value || "0", 10);
        return !isNaN(value) ? value : 0;
    };

$('.params2 tr').each( function() {
    var $row = $(this),
        count = toFloat($row.find('.calc-this-count input').val()), 
        price = toFloat($row.find('.calc-this-cost').text()),
        total = count * price;

    $row.find('calc-this-total').text(total.toFixed(2));
    totalcost += total;
});

$('#calc-total-price span').text(totalcost.toFixed(2));
于 2012-02-08T08:35:30.090 回答
1

console.log()将解决您的所有问题:

$('.params2 tr').each(function(){
    var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
    var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
    $('.calc-this-total',$(this)).html(count*price);
    totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
    console.log(count, price, totalcost)
});

在您不了解的地方添加更多日志记录。我不是刚刚告诉你使用日志记录吗?:)

于 2012-02-08T08:23:03.750 回答