[英]Tree traversal using jQuery
<ul id="org" style="display:none">
<li id="visited"><a href="#" class="ui-link">ROOT</a>
<ul id="main_child_ul" class="children">
<li><a href="#">Acura</a>
<ul>
<li><a href="#">Audi</a>
<ul>
<li><a href="#">BMW</a>
<ul>
<li><a href="#">Ferrari</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Cadillac</a>
<ul>
<li><a href="#">Acura1</a>
<ul>
<li><a href="#">Audi1</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">BMW1</a></li>
<li><a href="#">Cadillac1</a>
<ul>
<li><a href="#">Ferrari1</a></li>
</ul>
</li>
</ul>
</li>
</ul>
这是我的html UL LI树结构。
我想生成这个树结构的JSON。 此列表是动态生成的。
我正在使用jquery - 这是我的代码 - 我在这里得到了这篇文章的帮助 -
function processOneLi(node) {
var aNode = node.children("a:first");
var retVal = {
"link": aNode.attr("href"),
"title": aNode.text()
};
node.find("> .children > li").each(function() {
if (!retVal.hasOwnProperty("nodes")) {
retVal.nodes = [];
}
retVal.nodes.push(processOneLi($(this)));
});
return retVal;
}
function json_output()
{
$("#org > li").each(function() {
out.push(processOneLi($(this)));
});
console.log("got the following JSON from your HTML:", JSON.stringify(out));
}
这对于较小的树只生成json很好 - 我希望解决方案通用。 此解决方案中的另一个问题是它多次重复相同的节点。 请帮助,我被困在我的项目中。
像这样的东西?
function generateTree($node, result) {
result = result || {'nodes' : []};
$node.children('li').each(function(){
var $this = $(this);
var anch = $this.children('a').get(0);
var elem = {
"link": anch.href,
"title": anch.innerHTML,
"nodes" : []
};
if($this.has('ul'))
generateTree($this.children('ul'), elem);
result.nodes.push(elem);
});
return result.nodes; //or just return result.nodes[0] to access the root as object. But the existing one will be generic in case you are setting up for a class selector for multiple ul's as root.
}
将其调用为
var resTree = generateTree($("#org"));
console.log(JSON.stringify(resTree));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.