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 に入れる - 完璧に動作します。

しかし、totalcost の結果は NaN です。なんで?

4

2 に答える 2

2
  1. [一般] parseFloat() を必要以上に使用しないでください
  2. [一般] 繰り返しコードを関数に移動
  3. [jQuery] コンテキストおよびキャッシュ ノード ($row) に対して .find() を使用する
  4. [一般] String.replace() の仕組みを見てください
  5. [一般] float を表示するには 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 に答える