1. 程式人生 > >簡單遞歸寫側邊菜單欄

簡單遞歸寫側邊菜單欄

() data $.ajax nbsp urn += false com bubuko

htm:

<div id="main">

</div>

data:

{
    "code": 100,
    "content": {
        "rows": [
            { "id": "1", "name": "父節點1", "url": "www", "pid": "0" },
            { "id": "4", "name": "父節點11", "url": "", "pid": "1" },
            { "id": "13", "name": "父節點111", "url": "", "pid": "4" },
            { "id": "14", "name": "父節點112", "url": "", "pid": "4" },
            { "id": "5", "name": "父節點12", "url": "", "pid": "1" },
            { "id": "6", "name": "父節點13", "url": "", "pid": "1" },
            { "id": "2", "name": "父節點4", "url": "", "pid": "0" },
            { "id": "7", "name": "父節點41", "url": "", "pid": "2" },
            { "id": "8", "name": "父節點42", "url": "", "pid": "2" },
            { "id": "9", "name": "父節點43", "url": "", "pid": "2" },
            { "id": "3", "name": "父節點5", "url": "", "pid": "0" },
            { "id": "10", "name": "父節點51", "url": "", "pid": "3" },
            { "id": "11", "name": "父節點52", "url": "", "pid": "3" },
            { "id": "12", "name": "父節點53", "url": "", "pid": "3" }
        ]
    },
    "message": "成功"
} 

js:

 //主方法,運用遞歸實現
var createTree = function(jsons, pid) {
    if (jsons != null) {
        var ul = <ul class="nav">;
        for (var i = 0; i < jsons.length; i++) {
            if (jsons[i].pid == pid) {
                ul += <li class="item"> + jsons[i].name + "</li>";
                ul 
+= createTree(jsons, jsons[i].id); } } ul += "</ul>"; } return ul; } //調用 $.ajax({ url: data/menu.json, dataType: json, type: get, async: false, success: function(data) { if (data.code == 100) { var treeData = data.content.rows;
var ul = createTree(treeData, 0); $("#continer").append(ul); } } }); $(#continer li).on("click",function(){ var nextMenu=$(this).next(ul);if(nextMenu.length>0){ $(nextMenu).show().siblings(ul).hide(); } })

技術分享圖片

簡單遞歸寫側邊菜單欄