javascript - 使用 native javascript/HTML 创建 Html TreeView

标签 javascript html css

我需要使用 native JavaScript 从已创建的对象中创建一个 HTML/CSS TreeView ,如示例中所示。

请提出建议,

BR

最佳答案

您可以首先构建嵌套结构,然后使用递归方法从该数据创建 html,如果当前元素具有 Children 属性,您可以使用该 Children 数组作为数据参数再次调用该函数。

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;
}

关于javascript - 使用 native javascript/HTML 创建 Html TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61192082/

相关文章:

javascript - 使用 clone() 绑定(bind)重复事件

javascript - 使用 javascript 的 DOM 操作挂起 UI 线程

html - 图像一直低于组 div 中的其余图像?

html - HTML 表格的 CSS 样式以强制执行大小限制

internet-explorer - CSS3 动画在 IE9 中不工作

javascript - 如何更改javascript函数中的标签文本?

javascript - Jquery 删除类失败

javascript - 使用 `content` 属性作为 HTML 模板

javascript - 尝试绑定(bind)多个 Meteor 模板事件时出错

html - 文本流出 <p> 元素,溢出隐藏且不会居中