微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 解析数据以创建导航窗格

我有这个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可以为我提供所有站点和子站的列表:

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(地图);将输出类似于此的对象:

{
    "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", ...],
}

从中您可以创建元素列表.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。