layui 載入二級選單
想要使用layui+template 展示後臺管理的二級導航欄。
載入資料格式如下:{
"error": 0,
"desc": "請求成功",
"data": [
{
"id": 1,
"typeName": "首頁資訊",
"parentId": null,
"children": [
{
"id": 2,
"typeName": "首頁分類",
"parentId": null,
"children": []
},
{
"id": 3,
"typeName": "首頁資訊",
"parentId": null,
"children": []
}
]
},
{
"id": 4,
"typeName": "課程管理",
"parentId": null,
"children": [
{
"id": 5,
"typeName": "課程分類",
"parentId": null,
"children": []
},
{
"id": 6,
"typeName": "課程管理",
"parentId": null,
"children": []
},
{
"id": 7,
"typeName": "情景案例",
"parentId": null,
"children": []
},
{
"id": 8,
"typeName": "必備知識",
"parentId": null,
"children": []
},
{
"id": 9,
"typeName": "特定思考題",
"parentId": null,
"children": []
},
{
"id": 10,
"typeName": "可選方案",
"parentId": null,
"children": []
},
{
"id": 11,
"typeName": "解決問題",
"parentId": null,
"children": []
},
{
"id": 12,
"typeName": "案例分析",
"parentId": null,
"children": []
},
{
"id": 13,
"typeName": "總結歸納",
"parentId": null,
"children": []
},
{
"id": 14,
"typeName": "考試自測",
"parentId": null,
"children": []
},
{
"id": 15,
"typeName": "智慧決策",
"parentId": null,
"children": []
},
{
"id": 16,
"typeName": "參考資料",
"parentId": null,
"children": []
}
]
},
{
"id": 17,
"typeName": "論壇管理",
"parentId": null,
"children": []
}
]
}
初次載入,我想用thymeleaf 的each遍歷,但是因為是二級的關聯關係,並不能展示出來,只能展示一級根目錄,二級目錄展示就報錯。說不能為空或不存在。好吧。問了下 別人說,需要遞迴。
由於只有兩級,並不是無限的層級,所以,我就簡單的寫了一下,並不是不想繼續考慮,因為層級越多,好像介面就沒有辦法展示,涉及到頁面中的處理,有個想法,也就不試試了。
直接上自己的介面處理:
/** * 把資料遞迴出來 * @param data 要解析的資料 * @param flag 是否是根節點;true:是,false,不是 */ var html=""; function iteratorData(jsonObject,flag) { if(jsonObject.length!=0){ for(var i=0;i<jsonObject.length;i++){ if(flag){ html += " <li class=\"layui-nav-item layui-nav-itemed\">\n" + " <a href=\"javascript:;\">"+jsonObject[i].typeName+"</a>"; if(jsonObject[i].children!=null && jsonObject[i].children.length>0){ html += "<dl class=\"layui-nav-child\">"; iteratorData(jsonObject[i].children,false); html += "</dl>"; } html +="</li>"; }else { html +="<dd><a href=\"javascript:;\">"+jsonObject[i].typeName+"</a></dd>"; } } } return html; }