在click和fillulate list元素上动态加载JSON

时间:2017-03-18 09:52:40

标签: javascript jquery json

我有几个JSON文件,我想使用javascript click事件动态加载它们并填充无序列表。我怎样才能做到这一点?我的解决方案不起作用。我应该使用像AngularJS这样的javascript框架吗?

这是我的代码:

<!-- start home -->
<span data-deck="home" class="load-map home-marker marker current-level node" data-toggle="modal" data-target="#myModal">
    <i class="fa fa-home"></i>
</span><!-- end home -->

<!-- start housing -->
<span data-deck="housing" class="load-map housing-marker marker current-level node" data-toggle="modal" data-target="#myModal">
    <i class="fa fa-building-o"></i>
</span><!-- end housing -->

<!-- start school -->
<span data-deck="school" class="load-map school-marker marker node" data-toggle="modal" data-target="#myModal">
    <i class="fa fa-graduation-cap"></i>
</span><!-- end school -->

JS

$('.load-map').click(function()
{
    var deck = $(this).attr('data-deck');
    $('.load-map').removeClass('current-level');
    $(this).addClass('current-level');
    alert(deck)

        $.ajax({ 
          type : 'GET', 
          url : 'data/' + deck + '.json', 
          async : true, 
          dataType : 'JSON', 
          success : function(result){
           var buffer="";
            $.each(result, function(index, val){ 
              for(var i=0; i < val.length; i++){ 
                var item = val[i]; 
                console.log(item.FlavourText);
                buffer+="<li data-type='"+item.type+"' data-tier='"+item.tier+"' class='stack__item'></li>";

              } 
              $('#card-data ul').html(buffer);
            });
          }
         });

    });

JSON示例

[
  {
    "Card #": 0,
    "Type": "Opportunity",
    "Tier": 1
  },
  {
    "Card #": 5,
    "Type": "Opportunity",
    "Tier": 2
  }
] 

1 个答案:

答案 0 :(得分:0)

从你的代码中理解起来并不容易,但是我发现你已经将ajax包装在另一个jquery对象中,这可能是不必要的。

  $('.load-map').click(function() {
  var deck = $(this).attr('data-deck');
  $('.load-map').removeClass('current-level');
  $(this).addClass('current-level');
  alert(deck)

    $.ajax({
      // rest of the code
    });

});

此点击处理程序中还有一个空setTimeout