首页 > 解决方案 > 在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();
    }
  }
}

标签: javascripthtml

解决方案


推荐阅读