解析数据以创建导航窗格
我有这个XML响应: http : //jsfiddle.net/ZeeHv/
我正在尝试使用转储中的信息创建这样的东西:
- Academic
- BM
- CMTTE
- DM
- PM
- ARCHIVE
- ASSOCIATIONS
- BM
- DM
- PM
最后,XML可以为我提供所有网站和子站的列表:
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和li标签以创建网站导航菜单?
JS过去常常得到XML:
function getAllSites(){ $().SPServices({ operation: "GetAllSubWebCollection", async: true, completefunc: function(xData, Status){ $(xData.responseXML).find("Web").each(function(){ console.log($(this).attr("Url")); }); } }); }
一个简单的解决方案是根据链接的深度构建索引图,深度由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", ...], }
从中您可以创建元素列表。