我想列出类别,并且在每个类别中我想列出子类别,所以我在这样的循环中运行循环,但不幸的是它像这样返回我:
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>");
});
});
});
});
<div class="container-fluid">
<div id="listview">
</div>
<div id='listviewchild'>
</div>
</div>
最佳答案
基本上,从您的代码中,您的类别将始终根据您拥有的 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>
关于Javascript 在循环内循环以获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090522/