【发布时间】:2021-04-14 14:11:52
【问题描述】:
我有一组名为 countries.json 的 JSON 文件中的数据。
此数据使用 ID #country 填充下拉列表。
当用户选择此下拉菜单并选择国家/地区时,会出现“#state”选项。
除了这里所有的console.logs,这可以将正确的数据输入控制台,但不能输入正确的选择标签:
const selectTag = document.getElementById("state");
document.getElementById("country").addEventListener("change", function() {
const country_change = document.getElementById("country").value;
console.log(country_change);
console.log(countries);
console.log(selectTag);
const statesArray = [];
const Ind = countries.findIndex(e => {
return e['name'] === country_change;
})
if(Ind != -1){
countries[Ind]['states'].forEach(e=> statesArray.push(e['name']));
}
statesArray.forEach(e => {
console.log(e);
const option = document.createElement('option');
option.setAttribute("value", "state.name");
option.innerText = e;
selectTag.appendChild(option);
})
});
选择标签如下:
<select name="country" id="country">
{% for country in countries %}
{% if profile.country == country.name %}
<option value="{{ country.name }}" selected>{{ country.name }}</option>
{% else %}
<option value="{{ country.name }}">{{ country.name }}</option>
{% endif %}
{% endfor %}
</select>
<select name="state" id="state">
{% for country in countries %}
{% for state in country.states %}
{% if profile.state == state.name %}
<option value="{{ state.name }}" selected>{{ state.name }}</option>
{% else %}
<option value="{{ state.name }}">{{ state.name }}</option>
{% endif %}
{% endfor %}
{% endfor %}
</select>
当我选择一个国家/地区时,我希望所有州都填充#state 选择标签。
但是,尽管 console.log 确实显示了用户选择的正确状态,但这并没有使用 id #state 填充选择标签。
目前我不确定是因为我没有为选项创建值还是没有创建,但是当我尝试添加值时,我现在不确定第二个参数是什么。
【问题讨论】:
标签: javascript for-loop dropdown