萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現表格列勾選顯示/隱藏與行列合計計算

功能需求

  • 頁面載入自動計算合計列。
  • 核取方塊控制對應列顯示/隱藏,並即時更新合計。
  • 隱藏列不參與合計。

核心 JS

$(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()));
                }
            });
        }
    });
}

HTML 結構

<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 防錯。

擴充建議

若資料量大,建議改用資料模型(陣列/物件)驅動畫面,計算完成後一次渲染,效能更佳。

copyright © 萬盛學電腦網 all rights reserved