Parsing data to create a navigation pane

2019-01-29 07:19发布

I have this XML response: http://jsfiddle.net/ZeeHv/

I'm trying to create something like this using the information from the dump:

<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>

In the end the XML can give me a list of all my sites and 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 

How can I go through this information and append ul and li tags to create a site navigation menu?

JS used to get XML:

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

1条回答
乱世女痞
2楼-- · 2019-01-29 07:43

A simple solution would be to build a map of indexes based on the depth of the links, the depth is determined by the number of / in the 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); will output an object similar to this:

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

From this you can create your list of elements.

查看更多
登录 后发表回答