很多时候,需要把服务器端的文件列表出来显示。
用treetable的树状功能表格,可以实现分层级显示文件列表,比直接显示文件路径直观了很多。下面是实现办法:
样例数据:例如文件路径如下
var res2 = {
data: [
{ name: "c:\\path\\gowork1", sep:"\\"},
{ name: "c:\\path\\gowork2", sep: "\\" },
{ name: "c:\\path\\gowork3", sep: "\\" },
{ name: "c:\\path\\gowork4", sep: "\\" },
{ name: "c:\\path1\\gowork", sep: "\\" },
{ name: "c:\\path2\\gowork", sep: "\\" },
{ name: "c:\\path3\\gowork", sep: "\\" },
]
}
function filterPath(res) {
var items = [];
var category = [];
var sep = "";
var leve = 1; //计算总的层级数量
var maps = res.data;
for (var i in maps) {
sep = maps[i]['sep'];
if (maps[i]['name'].indexOf(sep) > -1) {
var temp = maps[i]['name'].split(sep).length;
if (temp > leve) {
leve = temp;
}
}
}
//console.log(leve);
for (var i = 0; i < leve; i++) {
category[i] = {};
for (var d in maps) {
//当前路径的所有层级数组 C:\my\go\tuch\e 路径按\分割成数组
var arr = maps[d]['name'].split(sep);
var key = arr.slice(0,i+1).join(sep);
//如果路径层级大于i,表示有目录数据
if (i < arr.length) {
//当前i层级的目录 category[0] = {C: 对象}
//category[1] = {my: 对象}
//category[2] = {go: 对象}
category[i][ key ] = {
path: maps[d]['name'],
id: parseInt(i * 1000000000 + d),
};
}
}
}
//console.log(category);
for (var i = 0; i < category.length; i++) {
for (var key in category[i]) {
pid = 0;
if (i > 0) {
pkey = key.split(sep).slice(0, i).join(sep) ;
console.log(pkey)
pid = category[i - 1][pkey]['id'];
}
items.push({
name: key.split(sep)[i] ,
id: category[i][key]['id'],
parentId: pid
})
}
}
/*把所有加入第一级*/
console.log(items)
return items;
}
下面引入layui的treetable
var layer = layui.layer;
var treetable = layui.treetable;
treetable.render({
id: 'demo'
, treeColIndex: 0 //树形图标显示在第几列
, treeSpid: '0' //最上级的父级id
, treeIdName: 'id' //id字段的名称
, treePidName: 'parentId' //父级节点字段
, treeDefaultClose: false //是否默认折叠
, treeLinkage: false
, elem: '#demo'
, data: filterPath(res2)
, cols: [[ //表头
{ field: 'name', title: '文件', sort: true,width:500 }
]]
})
好了,树状结构显示介绍。 对treetable不熟悉的,可以百度相关资料。