How can I recursively create a UL/LI's from JSON data - multiple layers deep

前端 未结 7 802
暖寄归人
暖寄归人 2020-12-30 12:32

I am trying to use use the following JSON data to create the following similar structure in a recursive inner function with not much luck, really need some help and so if an

7条回答
  •  醉酒成梦
    2020-12-30 13:00

    Fiddle

    Code:

    JS

    var jsonstring = [{
      "id": '1',
      "children": [{
        "id": '2'
      }, {
        "id": '3',
        "children": [{
          "id": '4'
        }]
      }]
    }, {
      "id": '5'
    }];
    
     var htmlStr= recurse( jsonstring );
    $('#test').append(htmlStr);
    
    
    function recurse( data ) {
      var htmlRetStr = "
      "; for (var key in data) { if (typeof(data[key])== 'object' && data[key] != null) { var x=key*1; if(isNaN(x)){ htmlRetStr += "
    • " + key + ":
        "; } htmlRetStr += recurse( data[key] ); htmlRetStr += '
    • '; } else { htmlRetStr += ("
    • " + key + ': "' + data[key] + '"
    • ' ); } }; htmlRetStr += '
    '; return( htmlRetStr ); }

    HtML

    CSS

    li ul ul li {
        padding-left: 10px;
    }
    
    li ul ul ul {
        padding: 0px;
    }
    

提交回复
热议问题