javascript - 尝试从 JSON 文件中选择一个值以输出到 HTML
问题描述
所以我有 6 个 div,我想使用我提供的 JSON 代码将累积奖金值输出到每个 div。我的问题是我似乎无法选择累积奖金值,因为我收到以下错误。未捕获的类型错误:无法在 XMLHttpRequest.ourRequest.onload (js.js:10) 的 renderHTML (js.js:24) 处读取未定义的属性“大奖”
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>
解决方案
在你引用数据的 for 循环中,data[i].jackpots.jackpot
你试图引用的数组是“jackpots”而不是“data”,所以也许试试data.jackpots[i].jackpot
.
推荐阅读
- parsing - 您如何在 Antlr4 的语法操作中引用可选规则“规则名称?”?
- windows - 为什么取消选中“启用运行时主题”会禁用按 Ctrl + A 的全选?
- javascript - Angular 5 FormGroup 验证器 Web 服务结果未触发 ngIF hasError
- git - GitLab 中的分支保护
- javascript - 从“[object Object]”获取表单数据
- oracle - 您可以在同时连接不同元素的 listagg 函数中插入回车吗?
- node.js - 当机器人在 Teams 中发送消息时,我如何获得通知?
- python - 适用于 python 的 Sonarqube:未发现测试成功分数 - 未找到“tests.test_transformation_helper.TestCase”的资源
- java - 用于配置、生成、监控、停止长任务 java 的 rest 接口
- javascript - Vue - 使用插件作为原型