javascript - 基本,通过从另一个选择中选择选择选项
问题描述
</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>
基本上,我想要做的是在我的第二个选择上添加一个名为“ville”的选项,当我选择加拿大时,它会给我另一个选择中的 3 个城市,反之亦然。我不知道如何做这个练习。谢谢。我应该使用for,还是仅在其他条件可行的情况下使用。
解决方案
这将是一个解决方案:
// 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);
})
}
<select id="pays">
<option value="Canada">Canada</option>
<option value="France">France</option>
</select>
<select id="ville">
推荐阅读
- elasticsearch - 限制 Elasticsearch 中的字段长度值
- terratest - 将 terratest 与单独的 backend.hcl 文件一起使用
- mongodb - 检查所有过滤器是否存在于数据库中
- javascript - 在 React Native 上尝试 AsyncStorage
- laravel - 如何在 Laravel 中添加非 Laravel 网站/脚本
- xcode - 我无法在我的 MacBook Pro 中安装 Cocopods
- ruby-on-rails - Rails 5 和每 30 秒的神秘请求
- php - 使用 PHP 生成 PDF (TCPD)
- azure - Azure 应用程序配置警报从未解决
- python - 如何在 python 中运行 try、break 或 continue 以进行函数循环?