gpt4 book ai didi

javascript - 如何操作/设置对下拉菜单选择的 react ?

转载 作者:行者123 更新时间:2023-11-30 14:05:15 25 4
gpt4 key购买 nike

我试图让第二个下拉菜单出现,这取决于对第一个下拉菜单选择的 react /选择。我想要显示第二个下拉菜单,这取决于第一个下拉菜单的选择。

我尝试过使用 if 语句,但这些并没有帮助我进步。

    <select id="countries">
<option id="US" value="unitedStates" > United States </option>
<option id="CA" value="canada" > Canada </option>
</select>

<script type="text/javascript">
//Global variable for the Countries drop down menu
var country = document.getElementById('countries');

</script>

我想要显示第二个下拉菜单,其中包含美国或加拿大的城市列表,具体取决于所选择的城市。

最佳答案

试试这段代码:

var cities = {
unitedStates: ["New York", "Washington"],
canada: ["Toronto", "Ottawa"]
}

var country = document.getElementById('countries');
var city = document.getElementById('cities');

country.onchange = () => {
let v = cities[country.value];
city.innerHTML = v ? v.map(c => `<option id="${c}" value="${c}">${c}</option>`) : '';
}
<select id="countries">
<option></option>
<option id="US" value="unitedStates" > United States </option>
<option id="CA" value="canada" > Canada </option>
</select>
<select id="cities"></select>

这里我们在第二个 <input> 中更改每个选项取决于首先选择<input> .数据取自 cities对象。


UPD:如果你不需要在第一个组合中使用空值

var cities = {
"United States": ["New York", "Washington"],
"Canada": ["Toronto", "Ottawa"]
}

var districts = {
"New York": ["District 1", "District 2"],
"Washington": ["District 3", "District 4"],
"Toronto": ["District 5", "District 6"],
"Ottawa": ["District 7", "District 8"]
}

let option = d => `<option id="${d}" value="${d}">${d}</option>`;
var country = document.getElementById('countries');
var city = document.getElementById('cities');
var district = document.getElementById('districts');

country.innerHTML = Object.keys(cities).map(option);
linkComboBoxes(country, city, cities);
linkComboBoxes(city, district, districts);

function linkComboBoxes(input1, input2, data) {
input1.onchange = () => {
input2.innerHTML = data[input1.value].map(option);
input2.onchange && input2.onchange();
}
input1.onchange();
}
<select id="countries"></select>
<select id="cities"></select>
<select id="districts"></select>

关于javascript - 如何操作/设置对下拉菜单选择的 react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com