原生JS实现多叉树展开折叠交互及类与HTML关联方法咨询
非二叉多子节点树的原生JS渲染实现
现有代码的已知问题
document.createElement用法误解:原生JS普通DOM元素不支持通过第二参数直接传属性配置,你写的document.createElement("div", { id: "ndiv" })里的配置不会生效,而且给所有节点设置同一个固定id本身就不符合HTML规范- 树结构平铺无层级:直接把所有节点append到body上,没有按父子关系嵌套DOM,完全体现不出树的层级结构
- 变量引用错误:Tree类的show方法里直接循环
root.children,没有加this指向当前树实例的根节点,运行时会直接报未定义的错 - 缺少核心逻辑:没有给节点绑定点击事件,也没有记录节点的展开/收起状态,实现不了要求的交互
完整无第三方依赖实现
优化后的类定义
核心思路是让每个Node实例持有自身关联的DOM引用和状态值,渲染时按树的层级嵌套DOM,交互逻辑直接封装在节点方法里:
class Node { constructor(name) { this.name = name; this.parent = null; this.children = []; this.isExpanded = false; // 记录节点展开/收起状态 this.domRef = null; // 缓存当前节点的DOM引用 this.childWrap = null; // 缓存存子节点的容器元素 } // 渲染当前节点自身的DOM结构 renderSelf() { // 节点外层容器,加左缩进体现层级 const nodeBox = document.createElement('div'); nodeBox.style.marginLeft = '1.2rem'; // 可点击的节点标题 const title = document.createElement('div'); title.style.cursor = 'pointer'; title.textContent = this.isExpanded ? `▼ ${this.name}` : `▶ ${this.name}`; // 绑定点击切换事件 title.addEventListener('click', (e) => { e.stopPropagation(); // 阻止冒泡触发父节点的点击逻辑 this.toggleShow(); }); // 存子节点的容器,默认隐藏 this.childWrap = document.createElement('div'); this.childWrap.style.display = this.isExpanded ? 'block' : 'none'; // 组装节点DOM nodeBox.appendChild(title); nodeBox.appendChild(this.childWrap); this.domRef = nodeBox; // 如果当前是展开状态,递归渲染所有子节点 if (this.isExpanded) { this.children.forEach(child => { this.childWrap.appendChild(child.renderSelf()); }) } return this.domRef; } // 切换展开/收起状态 toggleShow() { this.isExpanded = !this.isExpanded; // 更新标题的箭头标识 this.domRef.firstChild.textContent = this.isExpanded ? `▼ ${this.name}` : `▶ ${this.name}`; // 重写子节点容器内容 this.childWrap.innerHTML = ''; if (this.isExpanded) { this.children.forEach(child => { this.childWrap.appendChild(child.renderSelf()); }) this.childWrap.style.display = 'block'; } else { this.childWrap.style.display = 'none'; } } // 辅助方法:快速添加子节点 addChild(childNode) { childNode.parent = this; this.children.push(childNode); return this; } } class Tree { constructor(root) { this.root = root; } // 把整棵树挂载到页面指定DOM容器 mount(parentEl) { parentEl.innerHTML = ''; parentEl.appendChild(this.root.renderSelf()); } }
页面使用示例
<!-- 页面上放一个树的挂载容器 --> <div id="tree-root"></div> <script> // 测试构建树结构 const rootNode = new Node('根节点'); const childA = new Node('子节点1'); const childB = new Node('子节点2'); const grandA = new Node('子节点1的孙节点'); // 组装树的父子关系 rootNode.addChild(childA).addChild(childB); childA.addChild(grandA); // 初始化树并渲染到页面 const myTree = new Tree(rootNode); myTree.mount(document.getElementById('tree-root')); </script>
树类和DOM的关联逻辑说明
- 不用反向从DOM节点查树数据:每个Node实例自己存着对应的DOM引用,操作时直接通过实例属性修改就行
- DOM层级完全和树的结构一致:子节点的DOM永远嵌套在父节点的子容器里,不会出现平铺混乱的问题
- 交互状态和数据状态同步:展开/收起的状态存在Node实例上,不会出现页面显示和内部数据脱节的情况
内容的提问来源于stack exchange,提问作者Karlos Margaritos
相关产品推荐
相关产品推荐

