Я использую document.write, потому что он отображает то, что я хотел. Это работает, но удалит другое содержимое страницы в идентификаторе, на котором я пытаюсь отобразить его. Есть ли способ отобразить это для l oop внутри id = "main"? Когда я пытаюсь использовать document.getElementById ("main"). Inner HTML, он будет отображать только последние данные в массиве, который является городом Normal. Вот и все. Кто-нибудь может мне помочь?
var cities = [
{ city: "Bloomington, IL",
latitude: "40.4842° N, 88.9937° W",
population: "77,962",
elevation: "797 feet (243 m) above sea level",
},
{ city: "Normal, IL",
latitude: "40.5142° N, 88.9906° W",
population: "54,742",
elevation: "869 feet (265 m) above sea level",
}
];
function displayCityInfo() {
var x = document.getElementById("cityInfo").value;
if(x==1){
document.write("<h2>Results</h2>");
for(i=0; i<cities.length; i++){
document.write("Welcome to the city of " + cities[i].city
+ ", latitude is " + cities[i].latitude + "<p>");
}
}
else if(x==2){
document.write("<h2>Results</h2>");
for(i=0; i<cities.length; i++){
document.write("Welcome to the city of " + cities[i].city
+ ", population is " + cities[i].population + "<p>");
}
}
else if(x==3){
document.write("<h2>Results</h2>");
for(i=0; i<cities.length; i++){
document.write("Welcome to the city of " + cities[i].city
+ ", elevation is " + cities[i].elevation + "<p>");
}
}
}
<body>
<h1>City Information</h1>
<label>Select an option:</label>
<select id="cityInfo" onchange="displayCityInfo()">
<option selected disabled>Select an option</option>
<option value="1" enabled>Latitude/Longitude</option>
<option value="2" enabled>Population</option>
<option value="3" enabled>Elevation</option>
</select>
<main id ="main">
</main>
</body>