javascript - 在javascript中展开和折叠树
问题描述
我有一棵像这样的小树(有很多孩子的树不是二元的):
class Node {
constructor(name) {
this.name = name;
this.parent = null;
this.children = [];
}
}
class Tree {
constructor(root) {
this.root = root;
}
}
我需要把它带到页面上。当您单击一个节点时,您将看到她的孩子。
root node
child node 1, child node 2
如果你再次按下节点,孩子们就会清理干净。
root node
清晰的js和html中有什么简单的解决方案吗?
谢谢大家!
UPD 如何链接类和html?可能是这个解决方案:
class Node {
constructor(name) {
this.name = name;
this.parent = null;
this.children = [];
}
showNode() {
const nDiv = document.createElement("div", { id: "ndiv" });
const newContent = document.createTextNode(this.name);
nDiv.appendChild(newContent);
document.body.appendChild(nDiv);
}
}
class Tree {
constructor(root) {
this.root = root;
}
show() {
for (const child of root.children) {
child.showNode();
}
}
}
解决方案
推荐阅读
- android - 地理围栏 API 是否需要 ACCESS_BACKGROUND_LOCATION 权限才能使应用程序在 Android 10(Q) 上的前台运行?
- arrays - 获取 Swift 数组中的第一个条目
- listview - Flutter :启用文本字段时,背景图像向上移动。“resizeToAvoidBottomInset”禁用滚动。我哪里错了?
- azure - 订阅中的活动消息时更新订阅
- c# - 如何防止 ScintillaNET 控件自动滚动?
- python - 列表数据存储和更新列表
- python - 需要有关此错误的帮助:只能将列表(而不是“str”)连接到列表
- kotlin-flow - kotlin flow 没有从不同的函数发出值
- tensorflow - 限制CNN中不相关图像的概率百分比
- blazor - 如何在 Blazor 中编写自定义值更改事件处理程序?