
JavaScript实现动态N阶表格展开与收起功能
本文介绍如何使用JavaScript构建类似FineReport的动态N阶表格展开与收起功能。该功能允许用户在表格中灵活地展开和收起数据,支持任意层级嵌套。
功能需求
目标是实现一个能够动态展开和收起表格数据的交互式界面,满足以下要求:
- 多层级展开: 支持任意深度(N阶)的嵌套数据展开。
- 灵活的展开方式: 支持横向或纵向展开,或根据数据结构自定义展开方式。
- 动态数据更新: 能够根据用户操作动态更新表格内容。
实现方案
实现该功能的核心在于巧妙的数据结构设计和递归算法的运用。
1. 数据结构:
立即学习“Java免费学习笔记(深入)”;
采用树形结构(例如嵌套数组或对象)来表示层级数据,例如:
const data = [
{ name: '一级目录1', children: [
{ name: '二级目录1.1', children: [{ name: '三级目录1.1.1' }] },
{ name: '二级目录1.2' }
] },
{ name: '一级目录2', children: [{ name: '二级目录2.1' }] }
];
2. 递归渲染:
使用递归函数遍历树形数据,动态生成表格行。每个节点根据是否有子节点,决定是否显示展开/收起按钮。
function renderTable(data, parentElement) {
const table = document.createElement('table');
parentElement.appendChild(table);
function renderRow(item, level) {
const row = table.insertRow();
const cell = row.insertCell();
cell.textContent = item.name;
cell.style.paddingLeft = level * 20 + 'px'; // 缩进
if (item.children && item.children.length > 0) {
const button = document.createElement('button');
button.textContent = '+';
button.onclick = () => toggleRow(button, item);
cell.appendChild(button);
}
}
function toggleRow(button, item) {
button.textContent = button.textContent === '+' ? '-' : '+';
const nextSibling = button.parentNode.parentNode.nextSibling;
if (nextSibling && nextSibling.classList.contains('child-row')) {
nextSibling.remove();
} else {
const newRow = table.insertRow();
newRow.classList.add('child-row');
item.children.forEach(child => renderRow(child, button.parentNode.cellIndex + 1));
}
}
data.forEach(item => renderRow(item, 0));
}
const container = document.getElementById('table-container');
renderTable(data, container);
3. 展开/收起逻辑:
toggleRow 函数控制展开和收起操作。点击按钮时,切换按钮文本('+' 或 '-'),并根据状态显示或隐藏子节点对应的行。
4. 横向/纵向展开:
通过调整renderRow函数中DOM元素的插入位置和样式,即可实现横向或纵向展开。
总结
通过以上方法,结合灵活的数据结构和递归算法,可以有效地实现类似FineReport的动态N阶表格展开与收起功能,满足用户对复杂表格数据交互的需求。 需要注意的是,对于非常庞大的数据,需要考虑性能优化,例如虚拟滚动等技术。










