问题描述
点击下拉列表中的选项,加载选项对应的列表信息。
给定HTML:
<html>
<head>
</head>
<body>
<h1>A few of the Game of Thrones characters</h1>
<form>
<label for="house">House</label>:
<select name="house" id="house">
<option value="" selected>Select a house</option>
</select>
</form>
<ul id="characters"></ul>
</body>
</html>
显示结果:
解决方法
我的:
// Write your code here
const houseElement = document.createElement("option");
houseElement.textContent = "Lannister";
houseElement.id = "Lannister";
houseElement.value="Lannister";
document.getElementById("house").appendChild(houseElement);
document.getElementById("house").addEventListener("change",e=>{
const ui1=document.createElement("li");
ui1.textContent="Tywin";
const ui2=document.createElement("li");
ui2.textContent="Cersei";
const ui3=document.createElement("li");
ui3.textContent="Jaime";
let ui4=document.createElement("li");
ui4.textContent="Tyrion";
if(e.target.value === "Lannister")
{
document.getElementById("characters").appendChild(ui1);
document.getElementById("characters").appendChild(ui2);
document.getElementById("characters").appendChild(ui3);
document.getElementById("characters").appendChild(ui4);
}
});
显示效果:
选中这个选项会加载下面的选项
参考答案:
/*
Game of Thrones characters
*/
// Character list. Each house has a name and a code
const houses = [
{
code: "ST",
name: "Stark"
},
{
code: "LA",
name: "Lannister"
},
{
code: "BA",
name: "Baratheon"
},
{
code: "TA",
name: "Targaryen"
}
];
// Return an array of characters belonging to a house
const getCharacters = houseCode => {
switch (houseCode) {
case "ST":
return ["Eddard", "Catelyn", "Robb", "Sansa", "Arya", "Jon Snow"];
case "LA":
return ["Tywin", "Cersei", "Jaime", "Tyrion"];
case "BA":
return ["Robert", "Stannis", "Renly"];
case "TA":
return ["Aerys", "Daenerys", "Viserys"];
default:
return []; // Empty array
}
};
// Create and return an HTML <option> tag
const createOptionElement = (text, value) => {
const element = document.createElement("option");
element.textContent = text;
element.value = value;
return element;
};
// Create and return and HTML <li> tag
const createLiElement = text => {
const element = document.createElement("li");
element.textContent = text;
return element;
};
const houseElement = document.querySelector("select");
// Fill the house list
houses.forEach(house => {
houseElement.appendChild(createOptionElement(house.name, house.code));
});
// Handle house change event
houseElement.addEventListener("change", e => {
// The value of the event target is the house code
const characters = getCharacters(e.target.value);
const characterElement = document.getElementById("characters");
// Empty the list
characterElement.innerHTML = "";
// Add each character to the list
characters.forEach(character => {
characterElement.appendChild(createLiElement(character));
});
});
效果: