我有一个 AJAX 调用返回以下 JSON:
{
"categories": [
{
"active": true,
"name": Cat1,
"items": [
{
"active": true,
"id": 1,
},
{
"active": true,
"id": 2,
}
]
},
{
"active": true,
"name": Cat2,
"items": [
{
"active": true,
"id": 3,
},
{
"active": true,
"id": 4,
}
]
}
]}
我想要发生的是,一旦单击父类别项目,顶级类别名称就会进入一个 ListView ,而底层项目 ID 就会进入另一个列表级别。
目前,我有用于创建顶级类别 ListView 的代码,如下所示(这是 JQM):
<div data-role="content">
<script id="Template-categories" type="text/x-jquery-tmpl">
<li data-theme="a" class="ui-btn ui-btn-icon-right ui-li ui-li-has-alt ui-btn-up-a">
<div class="ui-btn-inner ui-li ui-li-has-alt">
<div class="ui-btn-text">
<a href="#${name}" class="ui-link-inherit">
<h3 class="ui-li-heading">${name}</h3>
</a>
</div>
</div>
</li>
</script>
<ul data-role="listview" id="listview-categories" data-theme="a">
</ul>
这是 AJAX 请求:
<script> // JSONP for ALL
$(document).ready(function() {
$.ajax({
url: "http://####.heroku.com/api/all_categories.json",
data: "format=json",
cache: false,
dataType: "jsonp",
type: 'GET',
timeout: 5000,
success: function(data) {
$.each(data, function() {
$("#Template-categories").tmpl(data.categories).appendTo("#listview-categories");
});
$.each(data, function() {
// THIS IS WHERE I GET LOST! How to then break down the category 1 items and category 2 items into their own listview dynamically!
});
},
error: function()
{ alert('BOOOO Error');}
});
});
所以:我的顶层正在工作,我只需要进入第二层(.items
)即可列出从属于其父项(类别)的 View 。如果这是一个复杂的问题,甚至告诉我如何使用类别 1 的 if
语句手动执行 each
循环(例如 if name=Category 1
然后循环遍历 items 数组)这会很有帮助,因为我现在可以将其硬编码到 html 中。
谢谢!
编辑: 尝试过这段代码...
我想我不明白的一件事是为什么这不起作用......
success: function(data) {
$.each(data, function() {
$("#Template-categories").tmpl(data.categories).appendTo("#listview-categories");
});
$.each(data, function() {
if(data.categories.name == "Cat1"){
$("#Template-cat1").tmpl(data.categories.items).appendTo("#listview-cat1");
}
});
然后在我的模板中仅使用 ${id}
属性和其他内容来显示 items 数组中的值。
最佳答案
这实际上相当简单,真的。在当前模板中使用 {{each}}
创建子列表的语法。文档中有很好的示例:http://api.jquery.com/template-tag-each/
更新示例:
- 请注意,我已在示例中更正了 json 对象中的错误...
var myData = { categories: [ { active: true, name: "Cat1", items: [ { active: true, id: 1 }, { active: true, id: 2 } ] }, { active: true, name: "Cat2", items: [ { active: true, id: 3 }, { active: true, id: 4 } ] } ] }; $(function () {
$("#Template-categories").tmpl(myData).appendTo("#listview-categories"); });
<script id="Template-categories" type="text/x-jquery-tmpl">
<ul>
{{each categories}}
<li data-theme="a" class="ui-btn ui-btn-icon-right ui-li ui-li-has-alt ui-btn-up-a">
<div class="ui-btn-inner ui-li ui-li-has-alt">
<div class="ui-btn-text">
<a href="#${name}" class="ui-link-inherit">
<h3 class="ui-li-heading">${name}</h3>
</a>
</div>
<div> <ul>
{{each items}}
<li> item : ${name}</li>
{{/each}}
</ul> </div>
</div>
</li>
{{/each}}
</ul>
</script>
<div id="listview-categories"> </div>
关于jquery - 如何使用 jQuery 和 jQuery 模板基于嵌套 JSON 数据创建嵌套 ListView 。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863773/