我对JavaScript很陌生,最近我接到一个任务,要使用JSON在HTML上显示几个国家和一些有关它们的信息。 由于我还是一个初学者,我想知道如何使用。map和no.append或$来做。
<div class="country">
<div class="name"></div>
<img src="" alt="">
<div class="description"></div>
<div class="area"></div>
<div class="continent"></div>
</div>
let countries = [
{ name: "Russia",
description: "russia description",
area: "17,098,246 km2",
image: "./flags/Russia.png",
continent: "Europe",
},
{ name: "China",
description: "china description",
area: "9,596,961 km2",
image: "./flags/China.png",
continent: "Asia",
},
{ name: "India",
description: "india description",
area: "3,287,263 km2",
image: "./flags/India.png",
continent: "Asia",
},
{ name: "United States",
description: "usa description",
area: "9,833,520 km2",
image: "./flags/USA.png",
continent: "North America.",
},
];
这里有一个简单的方法,我们使用foreach迭代器循环您拥有的对象数组(country),而对于每个元素(country),我们将创建html元素并将它们直接附加到body中。在本例中,我保留了一些原始格式,以便您更好地理解。 注:在这里使用。map没有任何意义,因为您不需要改变任何信息
countries.forEach(country => {
document.body.innerHTML +=
'<div class="country">' +
'<div class="name">' + country.name + '</div>' +
'<img src="' + country.image + '" alt="">' +
'<div class="description">' + country.description + '</div>' +
'<div class="area">' + country.area + '</div>' +
'<div class="continent">' + country.continent + '</div>' +
'</div>'
});