2013-10-18 25 views
0

我有這樣的XML響應:http://jsfiddle.net/ZeeHv/解析數據來創建一個導航窗格

我試圖使用從垃圾堆裏的信息來創建這樣的事情:

<UL> 
    <li>Academic 
    <ul> 
     <li>BM</li> 
     <li>CMTTE</LI> 
     <li>DM</li> 
     <li>PM</li> 
    </ul> 
    </li> 
</ul> 
<ul> 
    <li>ARCHIVE</li> 
</UL> 
<ul> 
    <LI>ASSOCIATIONS 
    <ul> 
    <li>BM</li> 
    <li>DM</LI> 
    <li>PM</li> 
    </ul> 
    </LI> 
</ul> 

到底XML可以給我我所有的網站和subsits的列表:

https://hosted.demo.ca 
https://hosted.demo.ca/academic 
https://hosted.demo.ca/academic/bm 
https://hosted.demo.ca/academic/cmtte 
https://hosted.demo.ca/academic/dm 
https://hosted.demo.ca/academic/pm 
https://hosted.demo.ca/archive 
https://hosted.demo.ca/associations 
https://hosted.demo.ca/associations/bm 
https://hosted.demo.ca/associations/dm 
https://hosted.demo.ca/associations/pm 

我怎樣才能通過這個信息,並追加UL和李標籤來創建一個站點導航菜單?用於獲取XML

JS:

function getAllSites(){ 
    $().SPServices({ 
    operation: "GetAllSubWebCollection", 
    async: true, 
     completefunc: function(xData, Status){ 
     $(xData.responseXML).find("Web").each(function(){ 
     console.log($(this).attr("Url")); 
     }); 
    } 
    }); 
} 

回答

0

簡單的解決辦法是建立一個地圖基於鏈接的深度指標,深度是由/url數量決定。

var map = {}; //init the map 
for (var i = 0, l = webs.length; i < l; i++) { 
    //we create a index for our links based on the depth of them by `/` 
    var m = webs[i].attributes['Url'].value.substring(23, webs[i].attributes['Url'].value.length).split('/').length; 

    map[m] = map[m] || []; //make sure we leave alone the old values if there is none init with new array 
    map[m].push(webs[i].attributes['Url'].value); //push new value to node 
} 
console.log(map); 

console.log(map);將輸出類似這樣的對象:

{ 
    "1": ["https://hosted.demo.ca", "https://hosted.demo.ca/academic", "https://hosted.demo.ca/archive", ...], 
    "2": ["https://hosted.demo.ca/academic/bm", "https://hosted.demo.ca/academic/cmtte", ...], 
} 

從這裏就可以創建你的元素列表。

+0

你讓我非常接近我想要做的事情,但它看起來像你教我想分組在一起。 (即所有1級坐在一起,所有lv2站點都會去等等)。這不完全是我想要完成的。我已經更新了我的OP,向你展示我的意思 – Batman