废话不多说直接上代码
html代码我是引用了一个jq的插件作为样式插件名字为 jOrgChart 具体内容大家可以评论到下方
<div class="com">
<div class="TheEditor">编辑</div>
<div id='jOrgChart'></div>
</div>
js代码大家把url地址改成你们本地的假数据渲染,
$.ajax({
url: url,
success:function (data) {
//将一位数组改变成树状结构图
function treeObj(originObj){
//对象深拷贝
var obj ={};
for (key in originObj){
var val = originObj[key];
obj[key] = typeof val === 'object' ? arguments.callee(val):val;
}
//对象新增children键值,用于存放子树
obj['children'] = [];
return obj;
}
//data:带转换成树形结构的对象数组
//attributes:对象属性
function toTreeData (data, attributes) {
var resData = data;
var tree = [];
//找寻根节点
for (var i = 0; i < resData.length; i++) {
if (resData[i][attributes.pid] === ''|| resData[i][attributes.pid] === null) {
tree.push( treeObj(resData[i]) );
resData.splice(i, 1);
i--;
}
}
run(tree);
//找寻子树
function run(chiArr) {
if (resData.length !== 0) {
for (var i = 0; i < chiArr.length; i++) {
for (var j = 0; j < resData.length; j++) {
if (chiArr[i][attributes.id] === resData[j][attributes.pid]){
var obj = treeObj(resData[j]);
chiArr[i].children.push(obj);
resData.splice(j, 1);
j--;
}
}
run(chiArr[i].children);
}
}
}
return tree;
}
var data = data.data;
// 属性配置信息
var attributes = {
id: 'id',
pid: 'pid',
};
var treeData = toTreeData(data, attributes);alert( treeData )
//点击菜单渲染树形菜单
var showlist = $("<ul id='org' style='display:none'></ul>");
showall(treeData,showlist);
$("#jOrgChart"). append(showlist);
$("#org").jOrgChart( {
chartElement : '#jOrgChart',//指定在某个dom生成jorgchart
dragAndDrop : true //设置是否可拖动
//chartClass [默认= 'jOrgChart']-分配给生成的标记的样式类的名称。
//chartElement - 用于指定您想要附加OrgChart标记的HTML元素。[默认= '主体']
});
//循环递归显示数据数据
function showall(menu_list,parent) {
//循环人员列表
$.each(menu_list, function(index,val) {
if(val.children.length > 0){
var li = $("<li></li>");
var li_two = $("<li></li>");
li.append(
"<a class='hiw' οnclick='add_click(this)'id="+val.id+">" +
"<img class='img_hide' src="+ val.img +" >"+
"<p title="+ val.name +" pid="+ val.pid +">"+ val.name +"</p>"+
"<div class='je_jia' οnclick='jiw(this,event)'>-</div>"+
"</a>"
).append("<ul></ul>").appendTo(parent);
//递归显示
showall( val.children, $(li).children().eq(1) );
}else{
$("<li></li>").append("<a class='hiw' οnclick='add_click(this)'id="+val.id+">" +
"<img class='img_hide' src="+ val.img +" >"+
"<p title="+ val.name +" pid="+ val.pid +">"+ val.name +"</p>"+
"<div class='je_jia' style='display: none;' οnclick='jiw(this,event)'>-</div>"+
"</a>").appendTo(parent);
}
});
};
}
})