【问题标题】:Javascript loop inside a loop to Get JSON循环内的 Javascript 循环以获取 JSON
【发布时间】:2018-04-15 21:01:10
【问题描述】:

我想列出类别,并且在每个类别中我想列出子类别,所以我在这样的循环中运行循环,但不幸的是它像这样返回我:

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>

【问题讨论】:

    标签: javascript html json loops


    【解决方案1】:

    基本上,根据您的代码,您的类别将始终根据您拥有的 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>
    

    【讨论】:

    • 哦,非常感谢它成功了,我知道我的代码有问题,但找不到正确的逻辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多