萬盛學電腦網

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

JavaScript 實現 TreeView 無刷新展開與複選框聯動

ASP.NET TreeView 渲染為巢狀 <div> + CheckBox,需實現:父勾選→子全勾、子取消→父取消、子全勾→父勾選的三態聯動。

核心工具函數

// 向上查找指定標籤父節點
function getParentByTag(el, tag){
    tag = tag.toUpperCase();
    while(el && el.tagName.toUpperCase() !== tag){
        el = el.parentNode || el.parentElement;
    }
    return el;
}

// 遞歸設置子節點勾選狀態
function setChildChecked(root, checked){
    const inputs = root.getElementsByTagName('input');
    for(const el of inputs){
        if(el.type === 'checkbox') el.checked = checked;
    }
}

事件處理邏輯

function checkEvent(){
    const chk = event.srcElement;
    if(chk.tagName !== 'INPUT' || chk.type !== 'checkbox') return;

    const idPrefix = chk.id.substring(0, chk.id.indexOf('CheckBox'));
    const nodesDiv = document.getElementById(idPrefix + 'Nodes');

    if(chk.checked){
        // 1. 向上勾選所有父 CheckBox
        let parentDiv = getParentByTag(chk, 'DIV');
        while(parentDiv){
            const pId = parentDiv.id.substring(0, parentDiv.id.indexOf('Nodes')) + 'CheckBox';
            const pChk = document.getElementById(pId);
            if(pChk && pChk.type === 'checkbox') pChk.checked = true;
            parentDiv = getParentByTag(parentDiv, 'DIV');
        }
        // 2. 向下勾選所有子 CheckBox
        if(nodesDiv) setChildChecked(nodesDiv, true);
    }else{
        // 取消:向下取消所有子節點
        if(nodesDiv) setChildChecked(nodesDiv, false);
        // 注意:父節點是否取消需根據兄弟節點狀態決定,此處簡化處理
    }
}

// 服務端綁定
treeView.Attributes.Add("onclick", "checkEvent()");

邏輯圖解

用戶點擊 CheckBox
    ├─ 勾選 → 遞歸向上勾選父 → 遞歸向下勾選子
    └─ 取消 → 遞歸向下取消子 → (可選)檢查兄弟決定父狀態

現代化建議

棄用 WebForms TreeView,改用前端樹組件(zTree, jsTree, Ant Design Tree)配合 AJAX 載入數據,邏輯清晰、支援虛擬滾動、鍵盤操作、拖拽排序等豐富交互。

copyright © 萬盛學電腦網 all rights reserved