[英]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? 如何在jQuery中使用
countMe
类对仅表行的值求和?
HTML: 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
. 我需要
#sum
说$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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.