gpt4 book ai didi

javascript - JSON 和 Jquery : Create nested JSON from nested list elements

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:21:11 25 4
gpt4 key购买 nike

我创建了这个 jsfiddle:http://jsfiddle.net/mfnxm/1/

我正在尝试创建这个 JSON:

[{
"link":"/about",
"title":"About",
"nodes":[{
"link":"/staff",
"title":"Staff",
"nodes":[{
"link":"/heads",
"title":"Dept Heads"
},{
"link":"/support",
"title":"Support"
}]
},{
"link":"/location",
"title":"Location"
}]
},{
"link":"/contact",
"title":"Contact"
}]

来自这个无序列表:

<div id="tree">
<ul class=".sortable">
<li><a href="/about">About</a>
<ul class=".sortable">
<li><a href="/staff">Staff</a>
<ul class=".sortable">
<li><a href="/heads">Dept Heads</a></li>
<li><a href="/support">Support</a></li>
</ul>
</li>
<li><a href="/location">Location</a></li>
</ul>
</li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>

到目前为止,这是 javascript ( borrowed from here ) - 但它没有为我创建节点元素:

var out = [];
function processOneLi(node) {
var aNode = node.children("a:first");
var retVal = {
"link": aNode.attr("href"),
"title": aNode.text()
};
node.find("> .sortable > li").each(function() {
if (!retVal.hasOwnProperty("nodes")) {
retVal.nodes = [];
}
retVal.nodes.push(processOneLi($(this)));
});
return retVal;
}
$("#tree ul").children("li").each(function() {
out.push(processOneLi($(this)));
});

// Do something with data
$('#d').text(JSON.stringify(out));

我错过了什么?谢谢!

最佳答案

每次出现时,将 HTML 中的 class=".sortable" 替换为 class="sortable"(无句点)。

您还需要将 $("#tree ul").children("li").each(function() 更改为 $("#tree > ul > "li ").each(function() { 以避免冗余处理。

http://jsfiddle.net/mblase75/mfnxm/2/

关于javascript - JSON 和 Jquery : Create nested JSON from nested list elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7932931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com