gpt4 book ai didi

javascript - 从json中取出所有数据并显示在index页面

转载 作者:行者123 更新时间:2023-12-03 07:08:55 25 4
gpt4 key购买 nike

我有以下 json:

[
{
"countryId" : 0,
"countryImg" : "../img/france.jpg",
"countryName" : "France",
"countryInfo" : {
"headOfState" : "Francois Hollande",
"capital" : "Paris",
"population" : 66660000,
"area" : 643801,
"language" : "French"
},
"largestCities" : [
{"Paris" : "../img/paris.jpg"},
{"Marseille" : "../img/marseille.jpg"},
{"Lyon" : "../img/lyon.jpg"}
]
},

{
"countryId" : 1,
"countryImg" : "../img/germany.jpg",
"countryName" : "Germany",
"countryInfo" : {
"headOfState" : "Angela Merkel",
"capital" : "Berlin",
"population" : 81459000,
"area" : 357168,
"language" : "German"
},
"largestCities" : [
{"Berlin" : "../img/berlin.jpg"},
{"Munich" : "../img/munich.jpg"},
{"Hamburg" : "../img/hamburg.jpg"}
]
}
]

我需要将它放在我的index.html中,但是我不明白为什么我只得到第二个对象?我需要将两个对象放入索引中。也许我需要使用循环?我该如何正确地做到这一点?我有以下 JavaScript 代码:

$.ajax({
method: "POST",
url: "../data/data.json"
}).done(function (data) {
/*console.log(data);*/
localStorage.setItem('jsonData', JSON.stringify(data));
var dataFromLocStor = localStorage.getItem('jsonData');
var dataObject = JSON.parse(dataFromLocStor);
console.log(dataObject);

function Countries(){

this.getCountries = function () {
var ulListElem = document.getElementById("list-of-teams").children,
imgCountry = document.createElement('img');

for(country in dataObject){
/*console.log(dataObject[team]['teamName']);*/

imgCountry.setAttribute('src', dataObject[country]['countryImg']);
imgCountry.setAttribute("width", "400");
imgCountry.setAttribute("height", "300");
console.log(country);

ulListElem[0].innerHTML = dataObject[country]['countryId'];
ulListElem[1].innerHTML = dataObject[country]['countryName'];
ulListElem[2].appendChild(imgCountry);
ulListElem[3].innerHTML = dataObject[country]['countryInfo']['headOfState'];
ulListElem[4].innerHTML = dataObject[country]['countryInfo']['capital'];
ulListElem[5].innerHTML = dataObject[country]['countryInfo']['population'];
ulListElem[6].innerHTML = dataObject[country]['countryInfo']['area'];
ulListElem[7].innerHTML = dataObject[country]['countryInfo']['language'];
}
}
}

var countriesDate = new Countries();
countriesDate.getCountries();
});

最佳答案

您在循环内两次设置相同的 UI 元素(img 和 ul)。当循环第一次运行时,将从第一个数组元素开始设置值。当循环第二次运行时,相同的元素将被新值覆盖。

要正确显示 JSON 数组中的所有元素,您需要在 index.html 页面中使用两组 UI 元素,例如两个 img、两个 ul

关于javascript - 从json中取出所有数据并显示在index页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36689500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com