1

次のような行を持つテーブルがあります。

<tr>
    <th width="30"></th>
    <th width="30">Time</th>
    <th>Description</th>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">2.50</td>
    <td>I did this, and also that, then a little of something else.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Another description of time.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Yet one more item entered.</td>
</tr>
<tr class="total">
    <td><strong>Total:</strong></td>
    <td><strong>[calculate total here]</strong></td>
    <td>&nbsp;</td>
</tr>

私はjQueryを使用しており、時間を追加するときに発生する関数の一部として、td.timeセルのすべての数値を追加する必要があります。しかし、私の人生では、ループを書くのはあまり得意ではなく、それを理解することはできません。

すべてのtd.timeセルを調べて、数値を合計するためのコードが必要です。合計が取れたら、[ここで合計を計算]スポットに挿入できます。

ありがとう!

4

4 に答える 4

1

要素を選択し、eachメソッドを使用してそれらをループします。

var tot = 0;
$('td.time').each(function(){
  tot += parseFloat($(this).text());
});
于 2011-01-26T16:25:15.327 に答える
0

を使用:nth-child(2n)して、すべてのテーブル行の 2 番目の項目を調べることができます...

var total = 0.0;
$('table tr td:nth-child(2n)').each(function(){
        val = parseFloat($(this).html());
        if (val > 0)total += val;
});
$('#result').html(total);

または、時間列が同じクラスであるため、...

var total = 0.0;
$('.time').each(function(){
        val = parseFloat($(this).html());
        if (val > 0)total += val;
});
$('#result').html(total);

http://jsfiddle.net/WsSVQ/3/

于 2011-01-26T16:26:46.003 に答える
0

テーブルに id="TestTable" と合計時間 id="total_time" の TD がある場合

var total = 0;
$('#TestTable td.time').each(function(index) {
total = total + parseFloat(this.html());
});
$('#total_time').html(total);

于 2011-01-26T16:27:50.513 に答える
0

$('td[class*="time"]')

私が正しければ、これはクラス「時間」を持つすべての TD タグを選択します。
多分それはあなたが使いたいものですか?

于 2011-01-26T16:28:22.930 に答える