gpt4 book ai didi

javascript - 列的 SUM 总计

转载 作者:行者123 更新时间:2023-11-30 10:41:29 26 4
gpt4 key购买 nike

请引用之前的问题:Sum total for column in jQuery

我使用了 Aymen 的解决方案,但我对其进行了编辑以满足我的需要。它停止工作,我的代码如下所示,在 jsfiddle 中看到:http://jsfiddle.net/unKDk/15/

<table id="sum_table" width="300" border="1">
<tr class="titlerow">
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
<td>Strawberry</td>
<td>Total By Row</td>
</tr>
<tr>
<td class="rowAA">1</td>
<td class="rowAA">2</td>
<td class="rowBB">3</td>
<td class="rowBB">4</td>
<td class="totalRow"></td>
</tr>
<tr>
<td class="rowAA">1</td>
<td class="rowAA">2</td>
<td class="rowBB">3</td>
<td class="rowBB">4</td>
<td class="totalRow"></td>
</tr>
<tr>
<td class="rowAA">1</td>
<td class="rowAA">5</td>
<td class="rowBB">3</td>
<td class="rowBB">4</td>
<td class="totalRow"></td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>

Jquery部分是

var totals=[0,0,0,0,0];
$(document).ready(function(){

var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

$dataRows.each(function() {
$(this).find('.rowAA').each(function(i){
totals[i]+=parseInt( $(this).html());
});

$(this).find('.rowBB').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});

});
  1. 如何解决导致jquery计算错误的问题。
  2. 如何按行计算总数
  3. 我需要完全相同的类名。

最佳答案

我不太确定你想要什么,但如果你只想按列对所有行求和,请参见下文..

var totalsByRow = [0, 0, 0, 0, 0];
var totalsByCol = [0, 0, 0, 0, 0];
$(document).ready(function() {

var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");

$dataRows.each(function(i) {
$(this).find('td:not(.totalRow)').each(function(j) {
totalsByCol[j] += parseInt($(this).html());
totalsByRow[i] += parseInt($(this).html());
});
});

for (var i = 0; i < totalsByCol.length - 1; i++) {
totalsByCol[totalsByCol.length - 1] += totalsByCol[i];
}

$("#sum_table td.totalCol").each(function(i) {
$(this).html("total:" + totalsByCol[i]);
});

$("#sum_table td.totalRow").each(function(i) {
$(this).html("total:" + totalsByRow[i]);
});
});

DEMO

关于javascript - 列的 SUM 总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com