使用 javascript 将路径解析为嵌套 html 列表
我有多个路径字符串(每个叶节点一个),例如
项目1
项目2
包含一些子项的文件夹/子项目 3.1
包含一些子项的文件夹/子项目 3.2
与一些儿童的文件/分项 4.1
与一些儿童的文件/分项 4.2
其中项目 1、项目 2、子项目 3.1、 3.2、4.1、4.2是叶子节点;我想做的是构建一个像这样的嵌套 HTML:
<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>
或像这样的 JSON 对象:
[
{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"}
]
}
]
但我很难做到这一点。我在这上面花了10个小时,毫无效果。我愿意使用jquery。请您引导我走向正确的方向吗?我的 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 spent 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能希望研究“递归函数”,它应该为您提供解决此类问题有用的技术的良好开端。
You may wish to research into "recursive functions", it should give you a good start into the techniques useful for this sort of problem.
我发现最好的方法是使用 javascript 的 createElement 和递归函数构建 html 元素,最后将其附加到 DOM。
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.
它不在 jQuery 中,但也许这会有所帮助。我在网上寻找并没有找到解决方案后开发了这个。
http://www.chapleau.info/article/ArrayofUrlsToASitemap.html
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