我正在尝试使用JavaScript实现树表,但是我无法解决这个问题。
one
├── two
│ ├── five
│ └── six
├── three
└── four
└── seven
你们认为上面的效果可以实现吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<script>
var data = [{
id: 1,
name: "one",
pid: 0,
level: 0,
children: [{
id: 2,
name: "two",
pid: 1,
level: 1,
children: [{
id: 3,
name: "five",
pid: 2,
level: 2,
children: []
},
{
id: 4,
name: "six",
pid: 2,
level: 2,
children: []
}
]
},
{
id: 5,
name: "three",
pid: 1,
level: 1,
children: []
},
{
id: 6,
name: "four",
pid: 1,
level: 0,
children: [{
id: 7,
name: "seven",
pid: 6,
level: 2,
children: []
}]
}
]
}];
var icon = new Array('│ ', '├─ ', '└─ ');
function treeA(data) {
var str = "";
var childPrefix = "";
for (var i = 0; i < data.length; i++) {
console.log(data[i].name);
var node = data[i].children;
childTree(node);
}
}
function childTree(node) {
for(var i = 0; i<node.length; i++) {
var child = node[i];
if(i<node.length-1){
console.log(icon[1]+child.name);
} else {
console.log(icon[2]+child.name);
}
if(jQuery.isArray(child.children)){
childTree(child.children);
}
}
}
$(function () {
treeA(data);
});
</script>
</body>
</html>
console.log打印出来结果:
one
├─ two
├─ five
└─ six
├─ three
└─ four
└─ seven
这个结果是不对的,应该按照上面效果才对了。
https://codepen.io/linvic/pen...
直接看吧