我有以下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();
});
答案 0 :(得分:1)
您在循环内设置两次相同的UI元素(img和ul)。当循环第一次运行时,从第一个数组元素设置值。当循环第二次运行时,SAME元素将被新值覆盖。
要正确显示JSON数组中的所有元素,您需要在index.html页面中使用两组UI元素,例如两个img
,两个ul
等。