[英]Problems creating an HTML bulleted list from JSON data
I am have some JSON that I want to turn in to a bulleted list. 我有一些JSON,我想转入项目符号列表。 At each level there is a name field and a children field (apart from at the lowest level).
在每个级别都有一个名称字段和一个子字段(除了最低级别)。 I have tried using recursion to do it but I have run in to a problem.
我已经尝试过使用递归来完成它,但我遇到了一个问题。 Only the first child is displayed at all but the last level.
除最后一级外,只显示第一个孩子。 I have a feeling that some of my recursive calls might not be returning properly.
我有一种感觉,我的一些递归调用可能无法正常返回。 Here is the code I have so far:
这是我到目前为止的代码:
function load_menu(){
json_text=ajax_get("example.json");
json_tree=JSON.parse(json_text);
write_menu(json_tree.children,document.getElementById("level1"));
}
function write_menu(json,element){
for(i=0;i<json.length;i++){
var listitem=document.createElement("li");
element.appendChild(listitem);
var listitemtext=document.createElement("span");
listitem.appendChild(listitemtext);
listitemtext.innerText=json[i].name;
if(json[i].children){
listitemtext.setAttribute("onclick","toggle(this);");
var sublist=document.createElement("ul");
listitem.appendChild(sublist);
write_menu(json[i].children,sublist);
};
};
}
I end up with a tree that looks like this: 我最终得到一棵看起来像这样的树:
Level 1,1
Level 2,1
Level 3,1
Level 3,2
It should look like this: 它应该如下所示:
Level 1,1
Level 2,1
Level 3,1
Level 3,2
Level 2,2
Level 1,2
Level 2,3
I have checked through my JSON and it seems to be ok so I guess there must be a problem with the recursion somewhere. 我已经通过我的JSON检查了它似乎没问题,所以我想某处的递归一定存在问题。 Can anyone help me out here?
有人可以帮我从这里出去吗?
If you write for (i...
the JS interpreter will create a new variable i
if one doesn't exist, or reuse an existing one if it does exist. That's the problem here, because you need new loop variables in every level of recursion. 如果你写
for (i...
JS解释器将创建一个新的变量i
如果它不存在,或者重用现有的变量,如果它确实存在。这就是问题,因为你需要在每个级别的新的循环变量递归。
So the solution is to force creation of a variable on every level, by writing for (var i...
instead. 因此,解决方案是通过写入
for (var i...
而不是强制)在每个级别上强制创建变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.