I have a table like this :
HTML:
value1 value2 value3&
相关标签:
3条回答
2021-01-16 06:51
Copy and past the code on your editor
JQuery
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
var sum = 0
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
$('.total-combat', this).html(sum);
});
});
</script
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
2021-01-16 06:56
You can do it like following.
$('table tfoot td').each(function(index) {
var total = 0;
$('tbody tr').each(function() {
total += +$('td', this).eq(index).text(); //+ will convert string to number
});
$(this).text(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>2</td><td>3</td><td>4</td></tr>
<tr><td>7</td><td>1</td><td>2</td></tr>
<tr><td>32</td><td>58</td><td>4</td></tr>
</tbody>
<tfoot>
<tr><td></td><td></td><td></td></tr>
</tfoot>
</table>
Update: for dynamic total row.
var totalRow = '', columnNo = $('table tr:first td').length;
for (var index = 0; index < columnNo; index++) {
var total = 0;
$('table tr').each(function () {
total += +$('td', this).eq(index).text(); //+ will convert string to number
});
totalRow += '<td>' + total + '</td>';
}
$('table').append('<tr>' + totalRow + '</tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>2</td><td>3</td><td>4</td></tr>
<tr><td>7</td><td>1</td><td>2</td></tr>
<tr><td>32</td><td>58</td><td>4</td></tr>
</table>
2021-01-16 07:03
If you need create a new row dynamically with results, you can do it with append
function:
$(document).ready(function(){
var result = [];
$('table tr').each(function(){
$('td', this).each(function(index, val){
if(!result[index]) result[index] = 0;
result[index] += parseInt($(val).text());
});
});
$('table').append('<tr></tr>');
$(result).each(function(){
$('table tr').last().append('<td>'+this+'</td>')
});
});
See example here: FIDDLE