首页 > 解决方案 > 如何从下拉框中编写一个 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))
      }
});

但仍然没有产生预期的结果。

标签: javascriptjsonfor-loop

解决方案


你可以这样做:

每次国家下拉值更改时,更新所有状态选项。

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>


推荐阅读