0

我有一个动态生成的表,看起来像这样:

<table id="mytable">
    <thead>
        <tr>
            <td>col1</td>
            <td>col2</td>
            <td>col3</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>col1</td>
            <td class="col2">1</td>
            <td class="col3">2</td>
        </tr>
        <tr>
            <td>col1</td>
            <td class="col2">7</td>
            <td class="col3">4</td>
        </tr>
        <tr>
            <td>col1</td>
            <td class="col2">col2</td>
            <td class="col3">col3</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Totals</td>
            <td id="col2total"></td>
            <td id="col3total"></td>
        </tr>
    </tfoot>
</table>

如何获得tds 中具有类的值col2的总和并将总和添加到tdid col2total?由于此表是动态生成的,我不知道trtbody.

4

3 回答 3

2

试试这个:

var total = 0;
$(".col2").each(function() {
    total += parseFloat('0' + $(this).text(), 10);
})
$("#col2total").text(total);
于 2012-08-01T08:55:45.663 回答
0
var total = 0;
$("td.col2").each(function() {
    total += parseFloat($(this).text()) || 0;
});

$("#col2total").text(total);
于 2012-08-01T08:57:13.570 回答
0
$(document).ready(function(){ 
    var sum = 0; 
    $('.col2').each(function() { 
        sum += Number($(this).val()); 
    });

    $("#col2total").text(sum); 
});
于 2012-08-01T08:58:54.303 回答