2012-02-08 55 views
0

我有一个表,要计算每个元素,如:计数元素不起作用

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

然后萨姆所有calc-this-cost并把它TOTALCOST股利。 这是表:

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

计数的每个元素,并把结果钙这种成本 - 工作完美。

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

回答

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使用日志记录? :)

2
  1. [普通]不要parseFloat()比你更需要
  2. [普通]招重复代码的功能
  3. [jQuery的]使用.find()在上下文和缓存节点( $行)
  4. [普通]看与string.replace()是如何工作的
  5. [普通]看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));