json to nested unordered list

后端 未结 2 1723
南旧
南旧 2021-01-27 02:33

I am trying to convert a JSON into an unordered list in jQuery.This is my JSON data.

var myJSON = \"{name:\\\"Director\\\",children:[name:\\\"Exe Director1\\\",n         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-27 03:09

    You can use recursive function as follows. Everytime the function is called it returns a "UL", along with its child "LI".

    function generateMenu(data) {
    
        var ul = $("
      "); $(data).each(function (i, dir) { var li = $('
    • ' + dir.name + '
    • '); ul.append(li); if (dir.children != null && dir.children.length > 0) { li.append(generateMenu(dir.children)); } }); return ul; };

    Use it as :

    $("#some-div").append(generateMenu(myJsonData));

    The Json is,

    var myJsonData = JSON.parse('{"name": "Director","children": [{ "name": "Exe Director1" },{ "name": "Exe Director2" },{"name": "Exe Director3","children": [{ "name": "Sub Director1" },{ "name": "Sub Director2" },{"name": "Sub Director3","children": [{ "name": "Cameraman 1" },{ "name": "Cameraman 2" }]}]}]}');

提交回复
热议问题