xinxin?

JavaScript:使用递归构建树型菜单

使用递归函数将扁平数据转为树型结构,并渲染到页面

效果图:

代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>递归函数处理数据</title>
</head>

<body>
  <div class="nav" style="background-color: pink;">
  </div>
  <script>
    var data = [
      { id: 1, name: '衣服', pid: 0 },
      { id: 2, name: '裤子', pid: 0 },
      { id: 3, name: '外套', pid: 1 },
      { id: 4, name: '短裤', pid: 2 },
      { id: 5, name: '风衣', pid: 3 }
    ]
    function filterArray(data, parent){
      let temp = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].pid === parent) {
          temp.push(data[i])
          data[i].children = filterArray(data, data[i].id) //返回值是一个数组,又赋值给data[i].children
        }
      }
      return temp
    }
    let tree=filterArray(data,0)

    let nav = document.querySelector('.nav');
    function setDomTree(data, node) {
      let ul
      for (let i = 0; i < data.length; i++) {
          ul = document.createElement('ul')
          let li = document.createElement('li')
          li.innerHTML = data[i].name
          node.appendChild(ul)
          ul.appendChild(li)
          if (data[i].children.length !== 0) {
              let element = setDomTree(data[i].children, ul)
              ul.appendChild(element)
          }
      }
      return ul
    }
    setDomTree(tree,nav)
  </script>
</body>

</html>

 

posted on 2020-07-25 14:58  xinxin?  阅读(290)  评论(0编辑  收藏  举报

导航