W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
插件描述:根據(jù)特定的json格式生成無限級樹形菜單
Json 格式類似這樣( 完全可以根據(jù)自己的需要改 ):
var json = [{
"name": "中科慈航",
"code": "ZKCH",
"icon": "icon-th",
"child": [{
"name": "廣州中科慈航",
"icon": "icon-minus-sign",
"code": "GZZKCH",
"parentCode": "ZKCH",
"child": [{
"name": "廣州中科慈航天河區(qū)分行",
"code": "GZZKCHTQFH",
"icon": "",
"parentCode": "GZZKCH",
"child": []
}]
},
{
"name": "北京中科慈航",
"icon": "",
"code": "BJZKCH",
"parentCode": "ZKCH",
"child": [{
"name": "北京中科慈航中城區(qū)分行",
"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 是最重要的......是根據(jù)這兩個屬性來完成遞歸, 上面的方法也沒有優(yōu)化只是簡單的實現(xiàn) .
這是搜索功能 :
<script type="text/javascript">$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', '關(guān)閉');
$('.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', '關(guān)閉').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});</script>
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: