2012-02-08 10 views
0

を動作しません。完璧な仕事 - (関数計算で)カウント要素は、私は、テーブルを持っているなど、各要素を計算したい

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

各要素をカウントし、カルク、このコストがする置い結果: これはテーブルです。

しかし、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)); 
関連する問題