$(function(){ calcSum(); });
function trVisible(chk, index) {
$('#Tr' + index).css('display', chk.checked ? 'block' : 'none');
calcSum();
}
function calcSum() {
// 重置合計列為 0
$('#trSum').find('td').each(function(){
if ($(this).index() !== 0) $(this).text('0');
});
// 累加可見列
$('#tabrytj').find('tr').each(function(){
if ($(this).css('display') === 'block') {
$(this).find('td').each(function(){
var idx = $(this).index();
if (idx >= 1) {
var sumCell = $('#trSum').find('td:eq(' + idx + ')');
sumCell.text(parseFloat(sumCell.text()) + parseFloat($(this).text()));
}
});
}
});
}
<table>
<tr>
<td>分公司</td><td><select>...</select></td>
<td><input type="checkbox" onclick="trVisible(this,1)" checked>張1</td>
<td><input type="checkbox" onclick="trVisible(this,2)" checked>張2</td>...
</tr>
</table>
<table id="tabrytj" class="tableinfo">
<tr id="Tr1" style="display:block"><td>張1</td><td>124536</td>...</tr>
<tr id="Tr2" style="display:block">...</tr>
<tr id="trSum"><td></td><td>0</td><td>0</td>...</tr>
</table>
display: block/none 控制列可見性,css('display') 判斷是否參與計算。trSum 作為中介累加器,避免重複遍歷。parseFloat 防止字串連接,若資料可能含非數字需加 || 0 防錯。若資料量大,建議改用資料模型(陣列/物件)驅動畫面,計算完成後一次渲染,效能更佳。