计数元素不起作用

时间:2012-02-08 08:19:02

标签: javascript jquery counting

我有一张桌子,想要计算每个元素,如:

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。为什么呢?

2 个答案:

答案 0 :(得分:2)

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

    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));
    

答案 1 :(得分: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)
});

在您不理解某些内容的地方添加更多日志记录。我没有tell you使用日志记录吗? :)