请注意,我是编码的新手,正在做一些简单的学校作业。所以请对我放轻松。 :-)
所以我的一个问题是创建一个网页,其中包含一个包含所有行星名称的数组。我很容易做到这一点。
<script>
var planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
</script>
到目前为止,还不错。下一步要求使用数组在选定对象中显示行星的名称。我也设法让这个工作起来,尽管它花了一些时间。
Planets
<select id="planetSelect">
<script>
for (var p = 0; p < 9; ++p) {
document.write("<option value='p'>");
document.write(planets[p]);
document.write("</option>");
}
</script>
</select>
明白了。现在我的页面显示一个带有所有行星名称的小下拉菜单...现在最后一步是让网页在下拉菜单中选择时显示行星的卫星数量和引力因子。 (这个信息可以很容易地用谷歌搜索,而不是我遇到的问题。)我不确定如何将信息正确地绑定(bind)到下拉选择/数组并显示它。不知道如何开始和进行。任何帮助表示赞赏! :-)
最佳答案
您可以将您的 JS 分离到另一个文件中并填充 <select>
元素与 <option>
通过动态创建标签。然后当<select>
元素变化你可以触发一组条件并将其写入<h1>
对于这个例子,我只是添加了火星和地球的信息。希望这对您有所帮助并助您一臂之力。 Fiddle
var planets = ["-", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
//Get the <select> element
selectElement = document.getElementById("planetSelect");
//Dynamically populate the select element with the option
for(var i=0; i<planets.length; i++){
option = document.createElement("option");
selectElement.append(option);
option.setAttribute("value", planets[i]);
option.innerText =planets[i];
}
//When the <select> element changes it will trigger a condition
//if it matches it will display the information in the <h1>
selectElement.onchange = function(){
//This will get the value of the selected option
item = selectElement.options[selectElement.selectedIndex].value;
moonData = document.getElementById("moonCount");
if(item == "Mars"){
moonData.innerHTML = "Mars has 2 moons.";
}
if(item == "Earth"){
moonData.innerHTML = "Earth has 1 moons.";
}
}
<select id="planetSelect">
</select>
<h1 id="moonCount">
</h1>
关于HTML 在数组的选择选项中显示信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53766014/