简体   繁体   中英

Problems creating an HTML bulleted list from JSON data

I am have some JSON that I want to turn in to a bulleted list. 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. 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.

So the solution is to force creation of a variable on every level, by writing for (var i... instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM