HTML 中的树形图

如何获得这个:


<ul>

  <input type="text" placeholder="A" />

  <ul>

    <input type="text" placeholder="B" />

    <ul>

      <input type="text" placeholder="D" />

    </ul>

    <ul>

      <input type="text" placeholder="E" />

    </ul>

  </ul>

  <ul>

    <input type="text" placeholder="C" />

    <ul>

      <input type="text" placeholder="F" />

    </ul>

    <ul>

      <input type="text" placeholder="G" />

    </ul>

  </ul>

</ul>

从中:


const graph = {

  A: ['B', 'C'],

  B: ['D', 'E'],

  C: ['F', 'G'],

  D: [],

  E: [],

  F: [],

  G: [],

 }

常量图的意思是:


        A

      /   \

     B     C

    / \   / \

   D   E F   G

不使用oop图。您可以从列表中删除输入,然后只需插入顶点的名称。


拉莫斯之舞
浏览 117回答 2
2回答

大话西游666

你需要通过二叉树算法即深度优先来绘制dom。算法是:绘制根元素,找到它的子元素从第一个孩子开始,画它,找到它的孩子继续重复步骤 2,直到到达树的底部。然后从步骤 2 转到下一个子项,并执行与第一个子项相同的步骤。通过执行上述步骤,我认为您可以使用深度优先二叉树算法轻松绘制 DOM。看看下面的示例<body><div id="root"></div></body>const graph = {&nbsp; A: ['B', 'C'],&nbsp; B: ['D', 'E'],&nbsp; C: ['F', 'G'],&nbsp; D: [],&nbsp; E: [],&nbsp; F: [],&nbsp; G: [],&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;const root = document.getElementById("root");&nbsp;&nbsp;&nbsp;const findchildren = (node) => graph[node]&nbsp;&nbsp;const drawNode = (node) => {&nbsp; &nbsp; const input = document.createElement("input");&nbsp;&nbsp; input.setAttribute("type", "text");&nbsp; input.setAttribute("placeholder", node);&nbsp; root.appendChild(input);&nbsp;&nbsp; const children = findchildren(node)&nbsp; if (children.length > 0) {&nbsp; &nbsp; children.forEach(item => drawNode(item))&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp;}&nbsp;&nbsp;drawNode("A")

繁星淼淼

我这样做,但并不享受。草稿,也许我会改进它,但我已经做了一整天,所以我累了。&nbsp;const dataset = {&nbsp; &nbsp;A: ['B', 'C'],&nbsp; &nbsp;B: ['D', 'E'],&nbsp; &nbsp;C: ['F', 'G'],&nbsp; &nbsp;D: [],&nbsp; &nbsp;E: [],&nbsp; &nbsp;F: [],&nbsp; &nbsp;G: [],&nbsp;}const $tree = document.querySelector('.tree')function graphToHTML(node, root) {&nbsp; if (Object.values(node)[0].length === 0) return&nbsp; let ul = document.createElement('ul')&nbsp; let input = document.createElement('input')&nbsp; input.placeholder = Object.values(node)[0][0]&nbsp; root.append(ul)&nbsp; ul.append(input)&nbsp; graphToHTML(&nbsp; &nbsp; { [Object.values(node)[0][0]]: dataset[Object.values(node)[0][0]] },&nbsp; &nbsp; ul&nbsp; )&nbsp; ul = document.createElement('ul')&nbsp; input = document.createElement('input')&nbsp; input.placeholder = Object.values(node)[0][1]&nbsp; root.append(ul)&nbsp; ul.append(input)&nbsp; graphToHTML(&nbsp; &nbsp; { [Object.values(node)[0][1]]: dataset[Object.values(node)[0][1]] },&nbsp; &nbsp; ul&nbsp; )}let ul = document.createElement('ul')let input = document.createElement('input')input.placeholder = Object.keys(dataset)[0]ul.append(input)$tree.append(ul)graphToHTML({ A: ['B', 'C'] }, ul)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript