</head>
<body>
<fieldset>
<legend>D'où venez-vous ?</legend>
<div>Pays:
<select id="pays">
<option value="1">Canada</option>
<option value="1">France</option>
</select>
</div>
<div>Ville:<select id="ville"onclick="myFunction()">
</select>
</div>
</fieldset>
</body>
</html>
基本上,我想做的是在我的第二个名为&#39;&#39;&#39;&#39; ville&#39;当我选择加拿大时,它会给我3个城市,其他选择,反之亦然。我不知道该如何做这个练习。谢谢。我应该使用for,还是只有if else条件才能起作用。
答案 0 :(得分:0)
这将是一个解决方案:
// Setting variables which cannot be redeclared
const pays = document.getElementById('pays');
const france = ['Paris', 'Lyon', 'Marseille'];
const canada = ['Toronto', 'Vancouver', 'Victoria'];
// If select element (#pays) changes
pays.addEventListener('change', () => {
// France
if (pays.value === 'France') {
createElement(france);
}
// Canada
else if (pays.value === 'Canada') {
createElement(canada);
}
});
// Create option elements
function createElement(country) {
const ville = document.getElementById('ville');
// Delete all values before adding new ones
ville.innerHTML = '';
// Use a loop for the array called "country"
country.forEach((e) => {
// Setting variables which could be redeclared within a block
let option = document.createElement('option');
let text = document.createTextNode(e);
// Appen the element with text
option.appendChild(text);
ville.appendChild(option);
})
}
&#13;
<select id="pays">
<option value="Canada">Canada</option>
<option value="France">France</option>
</select>
<select id="ville">
&#13;