如何使用jquery从JSON追加嵌套的li

时间:2017-03-24 10:56:39

标签: javascript jquery json

我想把json数据带到前端,如图所示。 我该怎么做,这是我的代码。我希望它嵌套在下面的图片中。

这是我用我的代码得到的距离。

HTML:

 </body>
   <div id="active"></div>
 </body>

JQuery的

<script>
   $.getJSON("active.json", function(result){
   $.each(result, function(i, field){
   var UniqueNames= $.unique(result.map(function (d) {
   return d.gpanel;
   }));
   $("#active").append('<li>'+UniqueNames[i]+'</li>');
   });
   });
</script>

JSON:

  [{"ID":"1","gpanel":"sfd","ptitle":"sdffd","panel":"1,2",
  "free":"yes","fees":"0.00"},
  {"ID":"2","gpanel":"sdfd","ptitle":"sdfds","panel":"1",
  "free":"yes","fees":"0.00"},
   {"ID":"3","gpanel":"sdf","ptitle":"sdf","panel":"1",
  "free":"yes","fees":"0.00"},
   {"ID":"4","gpanel":"sfd","ptitle":"fes","panel":"1",
  "free":"yes","fees":"0.00"},
  {"ID":"5","gpanel":"bbbfff","ptitle":"hgffg","panel":"1,2",
  "free":"yes","fees":"0.00"}
  ]
提前谢谢。 enter image description here

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

您可以尝试此代码

$.getJSON("active.json", function(result){
  var UniqueNames= $.unique(result.map(function (d) {
    return d.gpanel;
  }));
  var ul_block = $("<ul/>");
  $.each(UniqueNames, function(i) {
    $(ul_block).append('<li>' + UniqueNames[i] + '</li>');
  });
  $("#active").append(ul_block);
});

我在代码中做了一些更改,

1)用于获取单序列的代码已从循环中删除,因此即使您需要一次,它也不会每次处理

2)将循环从result更改为UniqueNames,因为您只显示这些名称

您可以对我的代码进行更改以获得所需的输出,即显示级别

解决方案2:

根据您提供的数据结构和条件,请检查此代码

$.getJSON("active.json", function(result) {
    var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance"];
    var ul_block = $("<ul/>");
    $.each(result, function(i, data) {
        console.log(data);
        var panels = data.panel.split(",");
        var uli_block = $("<ul/>");
        $.each(panels, function(j, jdata){
            var ulii_block = $("<ul/>");
            $(ulii_block).append($("<li/>").text(data.ptitle));
            $(uli_block).append($("<li/>").text(panel_arr[panels[j]])).append(ulii_block);
        });
        $(ul_block).append($("<li/>").text(data.gpanel).append(uli_block));
    });
    $("#active").append(ul_block);
});