开发者

parsing a path into a nested html list with javascript

I have multiple path strings (One for each leaf node) such as

item1

item2

Folder with some children / Sub-item 3.1

Folder with some children / Sub-item 3.2

Document with some children / Sub-item 4.1

Document with some children / Sub-item 4.2

Where item 1,item 2, Sub-item 3.1,3.2,4.1, and 4.2 are leaf nodes; And what I want to do is build a nested HTML like this:

  <ul>
        <li>item1
        <li>item2
        <li>Folder with some children
            <ul>
                <li>Sub-item 3.1
                <li>Sub-item 3.2
            </ul>

        <li>Document with some children
            <ul>
                <li>Sub-item 4.1
                <li>Sub-item 4.2
            </ul>
    </ul>

Or a JSON object like this:

[
     {title: "Item 1"},
     {title: "Item 2"},
     {title: "Folder with some children",
         children: [
             {title: "Sub-item 3.1"},
             {title: "Sub-item 3.2"}
         ]
     },
     {title: "Document with some children",
         children: [
             {title: "Sub-item 4.1"},
             {title: "Sub-item 4.2"}
         ]
     }
]

But I'm having a hard time doing this. I've spen开发者_高级运维t 10 hours on this to no avail. I'm open to using jquery. Please can you guide me in the right direction? My javascript is still not good enough to do these things on the fly.


You may wish to research into "recursive functions", it should give you a good start into the techniques useful for this sort of problem.


I found that the best way to do this was to build the html elements using javascript's createElement and a recursive function and just append it to the DOM in the end.


It's not in jQuery, but maybe this could help. I developed this after seeking the web and found no solution.

http://www.chapleau.info/article/ArrayofUrlsToASitemap.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜