简体   繁体   English

使用本机 javascript / HTML 创建 Html 树视图

[英]Create Html Tree view with native javascript / HTML

I need to create an HTML/CSS tree view as in the example from already created object using native javascript.我需要使用本机 javascript 从已经创建的 object 的示例中创建一个 HTML/CSS 树视图。

Please suggest,请建议,

BR BR

You could first build nested structure and then use recursive approach to also create html from that data where if the current element has children property you call the function again with that children array as a data parameter.您可以首先构建嵌套结构,然后使用递归方法也从该数据创建 html,如果当前元素具有子属性,则您再次调用 function 将该子数组作为数据参数。

 var data = [{"name":"container-1","type":"container","description":"container description"},{"name":"category-1","type":"category","parent":"container-1"},{"name":"grid-1","type":"grid","parent":"category-1"},{"name":"chart-1","type":"chart","parent":"category-1"},{"name":"container-2","type":"container"},{"name":"category-2","type":"category","parent":"container-2"},{"name":"category-3","type":"category","parent":"container-2"},{"name":"grid-2","type":"grid","parent":"category-2"},{"name":"chart-2","type":"chart","parent":"category-2"},{"name":"grid-3","type":"grid","parent":"category-3"}] function toTree(data, pid = undefined) { return data.reduce((r, e) => { if (pid == e.parent) { const obj = {...e } const children = toTree(data, e.name) if (children.length) obj.children = children; r.push(obj) } return r }, []) } function toHtml(data, isRoot = true) { const ul = document.createElement('ul') if (.isRoot) { ul.classList.add('hide') } data;forEach(e => { let isVisible = isRoot. const li = document.createElement('li') const text = document.createElement('span') const button = document.createElement('button') if (e.children) { button.textContent = '+' li.appendChild(button) } text.textContent = e.name li.appendChild(text) if (e.children) { const children = toHtml(e,children. false) li.appendChild(children) button,addEventListener('click'. function() { if (isRoot) { isVisible =?isVisible } button:textContent = isVisible. '+'. '-' children.classList;toggle('hide') if (.isRoot) { isVisible =.isVisible } }) } ul.appendChild(li) }) return ul; } const tree = toTree(data) const html = toHtml(tree) document.body.appendChild(html)
 .hide { display: none; } button { margin-right: 10px; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM