1. 程式人生 > >js無限極選單實現

js無限極選單實現

 欄目資料格式:

通常網站欄目的資料表應該是這樣子的,
$address = array(
    array('id'=>1  , 'address'=>'安徽' , 'parent_id' => 0),
    array('id'=>2  , 'address'=>'江蘇' , 'parent_id' => 0),
    array('id'=>3  , 'address'=>'合肥' , 'parent_id' => 1),
    array('id'=>4  , 'address'=>'廬陽區' , 'parent_id'
=> 3), array('id'=>5 , 'address'=>'大楊鎮' , 'parent_id' => 4), array('id'=>6 , 'address'=>'南京' , 'parent_id' => 2), array('id'=>7 , 'address'=>'玄武區' , 'parent_id' => 6), array('id'=>8 , 'address'=>'梅園新村街道', 'parent_id' => 7), array('id'=>9
, 'address'=>'上海' , 'parent_id' => 0), array('id'=>10 , 'address'=>'黃浦區' , 'parent_id' => 9), array('id'=>11 , 'address'=>'外灘' , 'parent_id' => 10) array('id'=>12 , 'address'=>'安慶' , 'parent_id' => 1) );

這是php輸出的欄目資料格式

 轉化成js的json物件就是這樣子的:

var data = [
    {id
: 1, address: "安徽", parent_id: 0}, {id: 2, address: "江蘇", parent_id: 0}, {id: 3, address: "合肥", parent_id: 1}, {id: 4, address: "廬陽區", parent_id: 3}, {id: 5, address: "大楊鎮", parent_id: 4}, {id: 6, address: "南京", parent_id: 2}, {id: 7, address: "玄武區", parent_id: 6}, {id: 8, address: "梅園新村街道", parent_id: 7}, {id: 9, address: "上海", parent_id: 0}, {id: 10, address: "黃浦區", parent_id: 9}, {id: 11, address: "外灘", parent_id: 10}, {id: 12, address: "安慶", parent_id: 1} ];

 根據最後一個找到整個家族(家譜樹)

//根據最後一個找到整個家族
function familyTree(arr, pid) {
    var temp = [];
    var forFn = function(arr, pid){
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item.id == pid) {
                temp.push(item);

                forFn(arr,item.parent_id);
            }
        }
    };
    forFn(arr, pid);
    return temp;
}

//console.log(familyTree(data,10));

 從頂級往下找到所有的子子孫孫(子孫樹)

//子孫樹,從頂級往下找到是有的子子孫孫
function sonsTree(arr,id){
    var temp = [],lev=0;
    var forFn = function(arr, id,lev){
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item.parent_id==id) {
                item.lev=lev;
                temp.push(item);
                forFn(arr,item.id,lev+1);
            }
        }
    };
    forFn(arr, id,lev);
    return temp;
}
//console.log(sonsTree(data,0));

 利用子孫樹生成一個樹形dom結構(例項)

//利用 子孫樹 生成dom結構
var tree = sonsTree(data,0);
var temp = [];
for(var i=0;i<tree.length;i++){
    var item = tree[i],u = "";
    if(i>0){
        u = "</ul>";
    }
    if(item['lev']==0){
        temp.push(u+'<li><a class="one">'+item.address+'</a><ul>');
    }else{
        temp.push('<li><a>'+item.address+'</a></li>')
    }
    if(i+1==tree.length){
        temp.push("</ul>")
    }
}
//console.log(temp.join(""));

本文連結:js遞迴演算法實現無限級樹形選單http://www.51xuediannao.com/javascript/digui_shu.html