json to nested unordered list

后端 未结 2 1729
南旧
南旧 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:15

    This is exactly what you need:

    Use the jQuery template API. This was once part of jQuery but is currently only available as plugin. However, I think jQuery will adopt this or a similar technique again soon.

    http://api.jquery.com/category/plugins/templates/

    Its super easy to use:

    $.tmpl("template", jsonObject)
    

    Here a small basic template example:

    $.tmpl(
        "
  • ${Id}${Name}
  • ", [{Id:1, Name:"Werner"}, {Id:2, Name:"Klaus"}] );

    This will result in the following jQuery HTML element that can be appended to anywhere:

  • 1 Werner
  • 2 Klaus
  • For your complex data, you can also iterate JSON sub objects using the "{{each}}" template notation. Here the code for your data and template:

    var data = {name:"Director",children:[{name:"Exe Director1"},{name:"Exe Director2"},{name:"Exe Director3", children:[{name:"Sub Director3_1"},{name:"Sub Director3_2"},{name:"Sub Director3_3",children:[{name:"Cameraman3_3_1"},{name:"Cameraman3_3_2"}]}]}]};
    
    var template = '\
        
      \
    • ${name}\
        \ {{each(childindex, child) children}}\
      • ${child.name}\
          \ {{each(child2index, child2) child.children}}\
        • ${child2.name}
        • \ {{/each}}\
        \
      • \ {{/each}}\
      \
    • \
    \ '; $('body').empty().append($.tmpl(template, data));

    Browsers Result:

    • Director
      • Exe Director1
      • Exe Director2
      • Exe Director3
        • Sub Director3_1
        • Sub Director3_2
        • Sub Director3_3
        • ...

    This can be tweaked to support full recursion by including nested templates... but im a lazy guy and the rest is todo for you.

    cheers, will

提交回复
热议问题