我想列出类别,在每个类别中我想列出子类别,所以我在这样的循环中运行循环,但不幸的是它会像这样返回我:
Category(Mobile)
Category(Laptop)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)
但我想要的是有人这样想:
Category(Mobile)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Category(Laptop)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)
这是我的代码:
$(document).ready(function()
{
var url="https://myjson";
$.getJSON(url,function(result){
$.each(result, function(i, field){
var categoryId=field.categoryId;
var categoryName=field.categoryName;
$("#listview").append("<h3>"+ categoryName + "</h3>");
$.each(field.subcategories, function(i, row){
var id=row.subCategoryId;
var subCategoryName=row.subCategoryName;
$("#listviewchild").append("<p>"+ subCategoryName + "</p>");
});
});
});
});
&#13;
<div class="container-fluid">
<div id="listview">
</div>
<div id='listviewchild'>
</div>
</div>
&#13;
答案 0 :(得分:4)
基本上,根据您的代码,您的类别将始终根据您拥有的html附加到子类别的上方。
这里的逻辑将附加为你需要的
的javascript
$(document).ready(function()
{
var url="https://myjson";
$.getJSON(url,function(result){
$.each(result, function(i, field){
var categoryId=field.categoryId;
var categoryName=field.categoryName;
$("#listview").append("<h3>"+ categoryName + "</h3>");
$.each(field.subcategories, function(i, row){
var id=row.subCategoryId;
var subCategoryName=row.subCategoryName;
$("#listview").append("<p>"+ subCategoryName + "</p>");
});
});
});
});
html
<div class="container-fluid">
<div id="listview">
</div>
</div>