前端树形UI的生成
对数据tree遍历主要有两种方式
1.1 第一种是广度遍历
广度遍历可以利用队列完成
1.2 第二种是深度遍历
深度遍历可以利用函数递归来完成
下面的实例就是利用函数递归来完成对数据的遍历,然后生成对应的UI,主要要注意tree的ui插入节点的判断,所以给数据加上到对父节点的索引。
先看效果图
HTML:代码
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> 10 <style> 11 * { 12 list-style: none; 13 padding: 0; 14 margin: 0; 15 } 16 17 ul { 18 margin: 10px; 19 color: palegoldenrod; 20 border-left: 2px dashed gray; 21 padding-left: 2px; 22 background: #95dcae; 23 padding-top: 4px; 24 } 25 26 ul > li { 27 margin-left: 5px; 28 background: greenyellow; 29 margin-bottom: 5px; 30 color: #0d95ff; 31 border-left: 2px dashed gray; 32 } 33 34 ul > li > li { 35 margin-left: 15px; 36 background: #d6dc8f; 37 } 38 ul > li > li >li{ 39 margin-left: 15px; 40 background: #7fdcc8; 41 } 42 </style> 43 </head> 44 <body> 45 </body> 123 </html>
JS代码
1 const data = { 2 name: "A", 3 parent: 'pa', 4 nodes: [ 5 {name: "B", parent: 'A', nodes: [{name: "F", parent: 'B',}]}, 6 {name: "C", parent: 'A',}, 7 { 8 name: "D", parent: 'A', nodes: [ 9 {name: "G", parent: 'D',}, 10 {name: "H", parent: 'D',}, 11 { 12 name: "I", parent: 'D', 13 nodes: [ 14 {name: "J", parent: 'I',}, 15 {name: "K", parent: 'I',}, 16 {name: "K1", parent: 'I',}, 17 {name: "K2", parent: 'I',}, 18 {name: "K3", parent: 'I',}, 19 {name: "K4", parent: 'I',}, 20 21 22 ] 23 24 }] 25 }, 26 {name: "E", parent: 'A',} 27 ] 28 }; 29 const treeData = [ 30 data, 31 {name: 'testTree', parent: 'wfx', nodes: [ 32 {name: 'testChildTree', parent: 'testTree'}, 33 {name: 'testChildTree01', parent: 'testTree'}, 34 {name: 'testChildTree02', parent: 'testTree'}, 35 {name: 'testChildTree03', parent: 'testTree'}, 36 ]}, 37 {name: 'testTree1', parent: 'wfx1', nodes: [ 38 {name: 'testChildTree1', parent: 'testTree1',nodes:[ 39 {name:'tree00001',parent:'testChildTree1'}, 40 {name:'tree00002',parent:'testChildTree1'}, 41 {name:'tree00003',parent:'testChildTree1'}, 42 {name:'tree00004',parent:'testChildTree1'}, 43 ] 44 45 } 46 47 ]}, 48 {name: 'testTree2', parent: 'wfx2', nodes: [{name: 'testChildTree2', parent: 'testTree2'}]}, 49 ]; 50 51 52 function tree(data) { 53 // 插入父节点,如果有父节点存在,找到父节点 54 if ($('.' + data.parent).length > 0) { 55 $('.' + data.parent).append('<li class="' + data.name + '">' + data.name + '</li>'); 56 57 } else { 58 // 如果没有父节点不存在,自己创建一个 59 $('body').append($('<ul class="' + data.name + '">').text(data.name)); 60 } 61 62 63 // 判断是否有子节点 64 if (Array.isArray(data.nodes)) { 65 data.nodes.forEach(item => { 66 tree(item) 67 }); 68 } 69 } 70 71 72 treeData.forEach(item => tree(item));