[英]Javascript loop inside a loop to Get JSON
I want to list Categories and inside each category I want to list subcategories, so I am running loop inside a loop like this, but unfortunately it is returning me like this: 我想列出类别,并在每个类别中列出子类别,所以我在这样的循环中运行循环,但不幸的是,它使我像这样返回:
Category(Mobile)
Category(Laptop)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)
But what I want is some think like this: 但是我想要的是这样的想法:
Category(Mobile)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Category(Laptop)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)
Here is my code: 这是我的代码:
$(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>
Basically, from your code, your category will always append on the above of your subcategory based on the html that u have. 基本上,从您的代码中,您的类别将始终基于您拥有的html附加在子类别的上面。
Here`s the logic that will append as what you need 这是将根据您的需要追加的逻辑
javascript 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 HTML
<div class="container-fluid">
<div id="listview">
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.