尝试从JSON文件中选择一个值以输出到HTML

时间:2018-10-19 18:14:03

标签: javascript json

所以我有6个div,我想使用我提供的JSON代码将累积奖金值仅输出到每个div。我的问题是,当出现以下错误时,我似乎无法选择累积奖金值。     Uncaught TypeError:无法读取未定义的属性“ jackpots”         在renderHTML(js.js:24)         在XMLHttpRequest.ourRequest.onload(js.js:10)

JSON

  {
  "jackpots": [
    {
      "jackpot": "417,961.29", 
      "game": "ElmStreet"
    }, 
    {
      "jackpot": "3,741,373.46", 
      "game": "MillionairGenie"
    }, 
    {
      "jackpot": "3,741,373.46", 
      "game": "TreasureFair"
    }, 
    {
      "jackpot": "70,004.09", 
      "game": "JacksPot"
    }, 
    {
      "jackpot": "14,749.68", 
      "game": "IrishRiches"
    }, 
    {
      "jackpot": "17,932.43", 
      "game": "CasinoReels"
    }
  ]
}

JS

    var pageCounter = 1;
var animalContainer = document.getElementsByClassName("jackpot");
var icon = document.getElementsByClassName('icon');
for (var i = 0 ; i < icon.length; i++) {
icon[i].addEventListener("click", function () {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'http://www.json-generator.com/api/json/get/bZlZOVDMKq?indent=2');
  ourRequest.onload = function() {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
      pageCounter++;
  };
  ourRequest.send();
})};

function renderHTML(data) {
  var htmlString = "";

for (var i = 0 ; i < animalContainer.length; i++) {
  animalContainer[i].innerHTML = "<p>" + data[i].jackpots.jackpot + "</p>"
 }
}

HTML

<section class="games-container">

    <div class="game Jackpot">
    <img class="icon" class="icon" src="jackpot.png" alt="">
    <label class="name" >Jackpot</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game TreasureFair">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >TreasureFair</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game Millionaire Genie">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >Millionaire Genie</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game Irish Riches">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >Irish Riches</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game ElmStreet">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >ElmStreet</label>
    <label class="jackpot" >$0</label>
    </div>

    <div class="game CasinoReels">
    <img class="icon" src="jackpot.png" alt="">
    <label class="name" >CasinoReels</label>
    <label class="jackpot" >$0</label>
    </div>

</section>

1 个答案:

答案 0 :(得分:0)

在for循环中,在其中引用数据data[i].jackpots.jackpot的地方,您要引用的数组是“ jackpots”而不是“ data”,因此可以尝试data.jackpots[i].jackpot