阅读(1394)
赞(0)
动态JSON树形菜单
2016-10-02 09:22:19 更新
插件描述:根据特定的json格式生成无限级树形菜单
Json 格式类似这样( 完全可以根据自己的需要改 ):
var json = [{
"name": "中科慈航",
"code": "ZKCH",
"icon": "icon-th",
"child": [{
"name": "广州中科慈航",
"icon": "icon-minus-sign",
"code": "GZZKCH",
"parentCode": "ZKCH",
"child": [{
"name": "广州中科慈航天河区分行",
"code": "GZZKCHTQFH",
"icon": "",
"parentCode": "GZZKCH",
"child": []
}]
},
{
"name": "北京中科慈航",
"icon": "",
"code": "BJZKCH",
"parentCode": "ZKCH",
"child": [{
"name": "北京中科慈航中城区分行",
"code": "BJZKCHZCFH",
"icon": "",
"parentCode": "BJZKCH",
"child": []
}]
}]
},
{
"name": "中科科技",
"code": "ZKKJ",
"icon": "icon-th",
"child": [{
"name": "广州中科科技",
"code": "GZZKKJ",
"icon": "icon-minus-sign",
"parentCode": "ZKKJ",
"child": [{
"name": "广州天河中科科技",
"code": "GZTHZKKJ",
"icon": "",
"parentCode": "GZZKKJ",
"child": []
}]
}]
}];
JS:
function tree(data) {
for (var i = 0; i < data.length; i++) {
var data2 = data[i];
if (data[i].icon == "icon-th") {
$("#rootUL").append("<li data-name='" + data[i].code + "'><span><i class='" + data[i].icon + "'></i> " + data[i].name + "</span></li>");
} else {
var children = $("li[data-name='" + data[i].parentCode + "']").children("ul");
if (children.length == 0) {
$("li[data-name='" + data[i].parentCode + "']").append("<ul></ul>")
}
$("li[data-name='" + data[i].parentCode + "'] > ul").append("<li data-name='" + data[i].code + "'>" + "<span>" + "<i class='" + data[i].icon + "'></i> " + data[i].name + "</span>" + "</li>")
}
for (var j = 0; j < data[i].child.length; j++) {
var child = data[i].child[j];
var children = $("li[data-name='" + child.parentCode + "']").children("ul");
if (children.length == 0) {
$("li[data-name='" + child.parentCode + "']").append("<ul></ul>")
}
$("li[data-name='" + child.parentCode + "'] > ul").append("<li data-name='" + child.code + "'>" + "<span>" + "<i class='" + child.icon + "'></i> " + child.name + "</span>" + "</li>") var child2 = data[i].child[j].child;
tree(child2)
}
tree(data[i]);
}
}
tree(json)
js和json只有 code 和 parentCode 是最重要的......是根据这两个属性来完成递归, 上面的方法也没有优化只是简单的实现 .
这是搜索功能 :
<script type="text/javascript">$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', '关闭');
$('.tree li.parent_li > span').on('click',
function(e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', '展开').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', '关闭').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});</script>