标签:ges end cat 广州 url value content pid var
1.先上效果图 (借鉴博客)

2.这边不做样式的只做结构
function toTreeData(data) {
var pos = {};
var tree = [];
var i = 0;
while (data.length != 0) {
if (data[i].pid == 0) {
tree.push({
id: data[i].id,
text: data[i].text,
children: []
});
pos[data[i].id] = [tree.length - 1];
data.splice(i, 1);
i--;
} else {
var posArr = pos[data[i].pid];
if (posArr != undefined) {
var obj = tree[posArr[0]];
for (var j = 1; j < posArr.length; j++) {
obj = obj.children[posArr[j]];
}
obj.children.push({
id: data[i].id,
text: data[i].text,
children: []
});
pos[data[i].id] = posArr.concat([obj.children.length - 1]);
data.splice(i, 1);
i--;
}
}
i++;
if (i > data.length - 1) {
i = 0;
}
}
return tree;
}
var data = [
{
"id": "CU201407140001",
"pid": "0",
"text": "壳牌中国"
},
{
"id": "CU201407140002",
"pid": "CU201407140001",
"text": "壳牌北京分公司"
},
{
"id": "CU201407140003",
"pid": "CU201407140001",
"text": "壳牌上海分公司"
},
{
"id": "CU201407140004",
"pid": "CU201407140001",
"text": "壳牌广州分公司"
},
{
"id": "CU201407140005",
"pid": "CU201407140001",
"text": "壳牌深圳分公司"
},
{
"id": "CU201407140006",
"pid": "CU201407140001",
"text": "壳牌武汉分公司"
},
{
"id": "CU201407140007",
"pid": "CU201407140001",
"text": "壳牌成都分公司"
},
{
"id": "CU201407140008",
"pid": "CU201407140001",
"text": "壳牌海南分公司"
}
];
$(function () {
$.ajax({
url:hostAddress+‘/api/Customer/GetCustomerName?customerid=CU201407140001‘,
type:‘GET‘,
contentType:‘application/json‘,
beforeSend: function (request) {
request.setRequestHeader(‘Authorization‘,token_type+access_token);
},
success:function(data){
var tree = toTreeData(data);
var orag="";
$.each(tree, function (key, value) {
$(‘#list‘).empty();
orag += " <li><span>" + value.text + "</span>";
if (value.children!=null)
{
$.each(value.children, function (k, v) {
orag += "<ul> <li><span>" + v.text + "</span></li>";
if (v.children!=null)
{
$.each(v.children, function (kk, vv) {
orag += "<ul> <li><span>" + vv.text + "</span></li>";
});
orag += "</ul>";
}
});
orag += "</ul>";
}
orag += "</li>";
console.log(orag);
$("#list").html(orag);
})
}
});
})
标签:ges end cat 广州 url value content pid var
原文地址:http://www.cnblogs.com/WJ--NET/p/7417448.html