Javascript 使用jQuery进行树遍历
这只是为较小的树生成json,我希望解决方案是通用的。这个解决方案的另一个问题是,它多次重复相同的节点。请帮帮我,我被困在我的项目里了。像这样的事情Javascript 使用jQuery进行树遍历,javascript,jquery,json,Javascript,Jquery,Json,这只是为较小的树生成json,我希望解决方案是通用的。这个解决方案的另一个问题是,它多次重复相同的节点。请帮帮我,我被困在我的项目里了。像这样的事情 function processOneLi(node) { var aNode = node.children("a:first"); var retVal = { "link": aNode.attr("href"), "title": aNode.te
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));
}
把它当作
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.
}
测试指南:嘿,我非常喜欢这个。我在帮你拉小提琴:)谢谢你,男人-看起来很完美-我会在动态列表生成中试用。@PSL我在这里也需要你的帮助吗?如果可能的话,可能吗?
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));