【发布时间】:2010-07-03 20:22:12
【问题描述】:
好的,现在我这里有一个无序列表:
<ul id="mycustomid">
<li><a href="url of Item A" title="sometitle">Item A</a>
<ul class="children">
<li><a href="url of Child1 of A" title="sometitle">Child1 of A</a>
<ul class="children">
<li><a href="url of Grandchild of A" title="sometitle">Grandchild of A</a>
<ul class="children">
<li><a href="url of Grand Grand child of A" title="sometitle">Grand Grand child of A</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="url of Item B" title="sometitle">Item B</a></li>
<li><a href="url of Item C" title="sometitle">Item C</a></li>
</ul>
基本上,我只想将此数据转换为 JSON 实体。我想在 jQuery 中完成这项工作,而且我认为我很难做到。上面的列表只是一个例子,实际上,我的列表理想情况下会有更多的孩子,并且可能有“n”级深(意思是,它会有孙子的孙子的孙子孙女......或更多)我已经失去了无数睡了几个小时,我想我哪儿也不去:(
我想提取这些东西:锚点内的文本、锚点的url和锚点的标题,并将它们放到一个JSON实体上
我上面的列表的 JSON 格式是这样的:
{
name: "Item A",
url: "url of Item A",
title: "sometitle",
children: [{
name: "Child1 of A",
url: "url of Child1 of A",
title: "sometitle",
children: [{
name: "Grandchild of A",
url: "url of Grandchild of A",
title: "sometitle",
children: [{
name: "Grand Grand child of A",
url: "url of Grand Grand child of A",
title: "sometitle",
children: []
}]
}]
}]
},
{
name: "Item B",
url: "url of Item B",
title: "sometitle",
children: []
},
{
name: "Item C",
url: "url of Item C",
title: "sometitle",
children: []
}
一些有用的参考资料:
Javascript 解决方案: Traversing unordered lists using Javascript/Jquery
^ 这可能有效,但我需要的 JSON 输出格式如上所示,而不是此脚本输出的格式:(
其他参考资料:
How do I put unordered list items into an array
请大家帮忙:(
很多个不眠之夜都让我头疼..(P.s - 我花了大约 40 多分钟的时间来编写整个页面以及代码)
【问题讨论】:
-
正在处理它。顺便说一句,您生成的 JSON 是一个对象数组,因此您应该有周围的 [ 和 ] 括号。
[ {}, {}, {} ] -
谢谢 Samuel,但我的应用程序似乎使用了无效的 JSON,并且它使用了上述格式 :) 感谢您的输入 :)
标签: jquery json tree list traversal