



// 假设你的表格结构是这样的,每行有data-id和data-parent-id
// ...▶...
// ...
// ...
// ...
document.addEventListener('DOMContentLoaded', () => {
const table = document.querySelector('table');
if (!table) return;
// 获取所有行,并构建一个父子关系映射
const rows = Array.from(table.querySelectorAll('tbody tr'));
const rowMap = new Map(); // id -> tr element
const childrenMap = new Map(); // parentId -> [childIds]
rows.forEach(row => {
const id = row.dataset.id;
const parentId = row.dataset.parentId;
rowMap.set(id, row);
if (parentId) {
if (!childrenMap.has(parentId)) {
childrenMap.set(parentId, []);
}
childrenMap.get(parentId).push(id);
// 默认隐藏所有子节点
row.style.display = 'none';
}
});
// 绑定点击事件
table.addEventListener('click', (event) => {
const targetRow = event.target.closest('tr[data-id]');
if (!targetRow || !targetRow.dataset.id) return;
const rowId = targetRow.dataset.id;
const isExpanded = targetRow.classList.toggle('expanded'); // 切换展开状态类
// 切换图标
const toggleIcon = targetRow.querySelector('.toggle-icon');
if (toggleIcon) {
toggleIcon.textContent = isExpanded ? '▼' : '▶';
}
// 递归处理子节点的显示/隐藏
function toggleChildren(parentId, show) {
const childrenIds = childrenMap.get(parentId);
if (!childrenIds) return;
childrenIds.forEach(childId => {
const childRow = rowMap.get(childId);
if (childRow) {
childRow.style.display = show ? '' : 'none';
// 如果是收起操作,并且子节点本身是展开的,也要收起其后代
if (!show && childRow.classList.contains('expanded')) {
childRow.classList.remove('expanded');
const childToggleIcon = childRow.querySelector('.toggle-icon');
if (childToggleIcon) childToggleIcon.textContent = '▶';
}
// 递归处理下一级子节点
toggleChildren(childId, show && childRow.classList.contains('expanded')); // 只有父节点展开且子节点自身是展开的才显示
}
});
}
toggleChildren(rowId, isExpanded);
});
});