json到嵌套的无序列表 [英] json to nested unordered list
问题描述
我正在尝试将JSON转换为jQuery中的无序列表.这是我的JSON数据.
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\",name:\"Exe Director2\",name:\"Exe Director3\",children:[name:\"Sub Director1\",name:\"Sub Director2\",name:\"Sub Director3\",children:[name:\"Cameraman 1\",name:\"Cameraman 2\"]]]}";
预期输出为
<ul>
<li>Director
<ul>
<li>Exe Director 1</li>
<li>Exe Director 2</li>
<li>Exe Director 3
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<li>Sub Director 3
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
我该怎么办!
干杯
推荐答案
这正是您所需要的:
使用jQuery模板API.它曾经是jQuery的一部分,但目前仅可作为插件使用.但是,我认为jQuery将很快再次采用这种技术或类似技术.
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/
它超级好用:
$.tmpl("template", jsonObject)
这是一个小的基本模板示例:
Here a small basic template example:
$.tmpl(
"<li><b>${Id}</b>${Name}</li>",
[{Id:1, Name:"Werner"}, {Id:2, Name:"Klaus"}]
);
这将导致以下jQuery HTML元素可以附加到任何地方:
This will result in the following jQuery HTML element that can be appended to anywhere:
对于复杂数据,您还可以使用"{{each}}"模板表示法来迭代JSON子对象.这里是您的数据和模板的代码:
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 = '\
<ul>\
<li>${name}\
<ul>\
{{each(childindex, child) children}}\
<li>${child.name}\
<ul>\
{{each(child2index, child2) child.children}}\
<li>${child2.name}</li>\
{{/each}}\
</ul>\
</li>\
{{/each}}\
</ul>\
</li>\
</ul>\
';
$('body').empty().append($.tmpl(template, data));
浏览器结果:
- 导演
- Exe Director1
- Director
- Exe Director1
- 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.
欢呼声, 会
这篇关于json到嵌套的无序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Exe Director1
Browsers Result:
- Director
- Exe Director1