報表頁常有這種需求:表格底下要有一列「合計」,而且使用者可以勾選要納入統計的人員,取消勾選的那一列就不計入。用 jQuery 搭配 display 控制顯示,再重算一次總和即可。
把合計列當成中間變數:先把每格初始化為 0,然後走訪所有「目前可見」的資料列,把每格的值累加到合計列對應的欄位上。隱藏的列直接跳過,這樣就達到了「勾選決定是否計入」的效果。
$(function () {
// 頁面載入時先算一次
calcSum();
});
// 由核取方塊控制某一列是否參與計算
function trVisible(chk, index) {
if (chk.checked) {
$("#Tr" + index).css("display", "block");
} else {
$("#Tr" + index).css("display", "none");
}
calcSum(); // 顯示狀態變了就重算
}
function calcSum() {
// 1. 合計列歸零
$("#trSum").each(function () {
$(this).find("td").each(function () {
if ($(this).index() != 0) { // 第一欄是標題,不清
$(this).text("0");
}
});
});
// 2. 逐列累加
$("#tabrytj").find("tr").each(function () {
if ($(this).css("display") == "block") { // 隱藏列不計
$(this).find("td").each(function () {
var index = $(this).index();
if (index >= 1) {
var tdValue = $("#trSum").find("td:eq(" + index + ")").text();
$("#trSum").find("td:eq(" + index + ")")
.text(parseFloat(tdValue) + parseFloat($(this).text()));
}
});
}
});
}
<table>
<tr>
<td>分公司</td>
<td><select><option>華南分公司</option></select></td>
<td><input type="checkbox" onclick="trVisible(this,1)" checked="checked" />張1</td>
<td><input type="checkbox" onclick="trVisible(this,2)" checked="checked" />張2</td>
<td><input type="checkbox" onclick="trVisible(this,3)" checked="checked" />張3</td>
</tr>
</table>
<table border="0" class="tableinfo" id="tabrytj">
<tr id="Tr1" style="display:block">
<td>張1</td><td>124536</td><td>124536</td><td>124536</td>
</tr>
<tr id="Tr2" style="display:block">
<td>張2</td><td>98765</td><td>88888</td><td>77777</td>
</tr>
<tr id="trSum">
<td></td><td>0</td><td>0</td><td>0</td>
</tr>
</table>
1. 用 display 判斷是否計入,太脆弱。 只要別的邏輯動了 style,統計就會出錯。改用 class 標記會清楚得多:
$("#tabrytj tr.excluded").length === 0 // 是否全部計入
2. 大量重複查詢,效能差。 迴圈裡反覆呼叫 $("#trSum").find("td:eq(n)"),每次都重新走一遍 DOM。應該先快取:
var $sumCells = $("#trSum td");
$("#tabrytj tr").each(function(){
$(this).find("td").each(function(i){
if (i === 0) return;
var cur = parseFloat($sumCells.eq(i).text()) || 0;
$sumCells.eq(i).text(cur + (parseFloat($(this).text()) || 0));
});
});
3. parseFloat 沒有防呆。 遇到空白或 "$1,200" 這類格式會得到 NaN,之後整欄都壞掉。加上 || 0 或使用 parseFloat(String(v).replace(/,/g,'')) 較穩妥。金錢計算更應避免浮點誤差,可改用整數「分」為單位運算。
4. 用 .toggle() 取代手動 display。 jQuery 會記住元素原本的 display 值,切換更乾淨:
$("#Tr" + index).toggle(chk.checked);
calcSum();
最後,若資料量很大,這種「每次勾選就重算全部」的做法會有延遲。此時更合適的架構是:初次載入時就把每列的小計算出來存進 data(),之後勾選只需把對應的小計加減到總和,不必重掃整張表。