如何用JavaScript递归展示树形结构的文件夹与媒体文件列表
解决方案:构建多级树形结构并渲染带Font Awesome图标的嵌套列表
步骤1:确认数据库返回的数组结构
确保从数据库获取的数组包含每个节点的核心字段:id(唯一标识)、parent_id(父节点ID,根节点为0)、name(名称)、type(类型:folder/file)。示例结构:
$mediaItems = [ ['id' => 1, 'parent_id' => 0, 'name' => '根目录', 'type' => 'folder'], ['id' => 2, 'parent_id' => 1, 'name' => '工作文档', 'type' => 'folder'], ['id' => 3, 'parent_id' => 2, 'name' => '项目方案.docx', 'type' => 'file'], ['id' => 4, 'parent_id' => 1, 'name' => '旅行照片.png', 'type' => 'file'], ['id' => 5, 'parent_id' => 2, 'name' => '会议记录', 'type' => 'folder'], ['id' => 6, 'parent_id' => 5, 'name' => '2024-05-20.md', 'type' => 'file'], ];
步骤2:编写递归函数构建树形结构
替换之前的buildTree_函数,使用以下递归逻辑生成层级结构:
function buildTree(array $items, int $parentId = 0): array { $tree = []; foreach ($items as $item) { if ($item['parent_id'] === $parentId) { // 递归查找当前节点的子节点 $children = buildTree($items, $item['id']); if (!empty($children)) { $item['children'] = $children; } $tree[] = $item; } } return $tree; } // 生成树形结构 $treeStructure = buildTree($mediaItems);
步骤3:递归渲染嵌套列表(含Font Awesome图标)
编写递归函数将树形结构转换为HTML,根据节点类型匹配对应图标:
function renderTreeHtml(array $tree): string { $html = '<ul class="tree-list">'; foreach ($tree as $node) { // 根据节点类型选择Font Awesome图标 $iconClass = $node['type'] === 'folder' ? 'fa-folder' : 'fa-file'; // 转义名称避免XSS $safeName = htmlspecialchars($node['name']); $html .= '<li>'; $html .= "<i class=\"fa {$iconClass}\" aria-hidden=\"true\"></i> {$safeName}"; // 如果存在子节点,递归渲染 if (isset($node['children'])) { $html .= renderTreeHtml($node['children']); } $html .= '</li>'; } $html .= '</ul>'; return $html; } // 生成最终HTML $treeHtml = renderTreeHtml($treeStructure);
步骤4:返回给Ajax响应
在Controller中返回JSON格式的响应,包含渲染好的HTML:
header('Content-Type: application/json'); echo json_encode([ 'success' => true, 'html' => $treeHtml ]); exit;
前端接收并渲染
通过Ajax请求获取HTML后,插入到页面容器中(以jQuery为例):
$.ajax({ url: '/path/to/your/controller', method: 'GET', dataType: 'json', success: function(res) { if (res.success) { $('#tree-container').html(res.html); } } });
注意事项
- 确保已加载Font Awesome样式库(建议本地引入,避免外链依赖)
- 递归函数需注意性能,若数据量过大,可考虑优化为非递归实现或分页加载
- 对用户输入的文件名做
htmlspecialchars转义,防止XSS攻击
内容的提问来源于stack exchange,提问作者Nagesh Katke
相关产品推荐
相关产品推荐

