



// 假设你的表格结构是这样的,每行有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); });});
以上就是HTML表格如何实现树形结构显示?有哪些实现方式?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1568364.html
微信扫一扫
支付宝扫一扫