2012-02-08 46 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));