javascript - 如何从下拉框中编写一个 For 循环来填充 JSON 文件中的第二个下拉框?
问题描述
我有一个 Jinja 循环填充国家的下拉框。这允许用户选择一个国家。但是我有第二个 Jinja for 循环填充状态的第二个下拉框。目前,第二个下拉框只是迭代列表中的每个状态(即 1000 秒)。
因此,我正在构建一个 JavaScript 来遍历 JSON 文件并收集用户选择的国家/地区的数据,以仅使用与该特定国家/地区相关联的州来填充该州的列表。
不幸的是,这就是我卡住的地方。我对 JS 中 for 循环的常见概念不太熟悉。
到目前为止,我可以选择这个:
document.getElementById("country").addEventListener("change", function() {
const country_change = document.getElementById("country").value;
console.log(country_change);
console.log(countries);
});
其中 country_change 是用户选择的国家,国家是整个 JSON 文件。
单击国家/地区日志我得到的第一个条目:
这就是我想要迭代的内容:
我可以将 JSON 文件中的所有国家/地区调用到 JS 中,现在当用户选择一个国家/地区时,我拥有该变量,所以现在我想查看该国家/地区的州及其相关州。
我从 w3 学校尝试了一个简单的 for 循环,只是为了看看结果如何——但我没有收集到任何真正有用的东西。我想我只需要在正确的方向上多一点推动。
编辑:只是试验:
document.getElementById("country").addEventListener("change", function() {
const country_change = document.getElementById("country").value;
console.log(country_change);
console.log(countries);
const Ind = countries.findIndex(e => {
return e['name'] === country_change
})
if(Ind != -1){
countries[Ind]['states'].forEach(e=>console.log(e))
}
});
但仍然没有产生预期的结果。
解决方案
你可以这样做:
每次国家下拉值更改时,更新所有状态选项。
function updateSelect({ node, values }) {
while (node.hasChildNodes()) node.removeChild(node.lastChild)
for (const value of values) {
const option = document.createElement("option")
option.value = option.textContent = value
node.appendChild(option)
}
}
// Sample data
const countries = [
{
name: "Germany",
states: ["Bavaria", "Berlin", "Saxony"]
},
{
name: "Austria",
states: ["Tyrol", "Vienna"]
}
]
const coutriesSelect = document.querySelector("#country")
const statesSelect = document.querySelector("#state")
updateSelect({
node: coutriesSelect,
values: countries.map(country => country.name),
})
// Update it on initialization
updateStatesSelect()
coutriesSelect.addEventListener("change", updateStatesSelect)
function updateStatesSelect() {
const countryName = coutriesSelect.value
const country = countries.find(country => country.name === countryName)
const states = country.states
updateSelect({
node: statesSelect,
values: states
})
}
<select name="country" id="country"></select>
<select name="state" id="state"></select>
推荐阅读
- python - 找不到 METIS dll
- c# - 在操作期间在 CosmosClient 中启用/禁用批量执行是否安全?
- c# - 将一个对象分配给另一个对象时是否设置了 DBSet<> 对象的 ID?
- spring-boot - 当我使用@ComponentScan 时没有显示弹簧启动执行器
- vb.net - 有没有办法在我的应用程序中添加“实时更新”通知?
- xcode - clang:错误:XCode 12 更新后链接器命令失败,退出代码为 1
- android - 从firebase实时数据库中单个子项下的多个推送ID中检索数据
- c++ - 为什么它不起作用?简单的多线程示例
- java - 有什么办法可以阻止这个页面直接跳转到另一个页面?
- android-studio - Flutter:找不到提供程序安装程序的本地模块描述符类