简体   繁体   中英

How can I get the sum of all table rows with a certain class in jQuery?

How can I sum the values of only table rows with the countMe class in jQuery?

HTML:

<div id="sum">$0</div>
<table>
    <tr>
        <th>id</th> <th>value</th>
    </tr>
    <tr class="countMe">
        <td>1</td> <td class="v">$10</td>
    </tr>
    <tr>
        <td>2</td> <td class="v">$20</td>
    </tr>
    <tr class="countMe">
        <td>3</td> <td class="v">$10</td>
    </tr>
    <tr>
        <td>4</td> <td class="v">$30</td>
    </tr>
</table>

I need the #sum to say $20 . How can I do that?

You can do something like this:

var sum = 0;

$('tr.countMe td.v').each(function() {
    sum += parseFloat($(this).text().slice(1));
});

$('#sum').text(sum);

Try

$(function() {
 var countme = $('.countMe .v'), total=0;
    countme.each(function(key,val) {
        total += parseFloat($(this).text().slice(1));
    });
    $('#sum').html('$'+total);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM