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 載入數據,邏輯清晰、支援虛擬滾動、鍵盤操作、拖拽排序等豐富交互。