创建相互依赖的下拉列表可以通过以下步骤实现:
<select id="mainList"></select>
<select id="subList"></select>
var mainList = document.getElementById("mainList");
var subList = document.getElementById("subList");
var data = {
option1: ["subOption1", "subOption2", "subOption3"],
option2: ["subOption4", "subOption5"],
option3: ["subOption6", "subOption7", "subOption8"],
};
mainList.addEventListener("change", function() {
var selectedOption = mainList.options[mainList.selectedIndex].value;
updateSubList(selectedOption);
});
function updateSubList(selectedOption) {
subList.innerHTML = ""; // 清空从属列表的选项
var subOptions = data[selectedOption]; // 获取对应的从属列表选项
// 创建从属列表的选项并添加到从属列表元素中
for (var i = 0; i < subOptions.length; i++) {
var option = document.createElement("option");
option.text = subOptions[i];
subList.add(option);
}
}
完整的代码示例:
<select id="mainList"></select>
<select id="subList"></select>
<script>
var mainList = document.getElementById("mainList");
var subList = document.getElementById("subList");
var data = {
option1: ["subOption1", "subOption2", "subOption3"],
option2: ["subOption4", "subOption5"],
option3: ["subOption6", "subOption7", "subOption8"],
};
mainList.addEventListener("change", function() {
var selectedOption = mainList.options[mainList.selectedIndex].value;
updateSubList(selectedOption);
});
function updateSubList(selectedOption) {
subList.innerHTML = "";
var subOptions = data[selectedOption];
for (var i = 0; i < subOptions.length; i++) {
var option = document.createElement("option");
option.text = subOptions[i];
subList.add(option);
}
}
</script>
这样,当主列表的选项改变时,从属列表的选项会根据主列表选项的值进行更新。根据实际需求,可以修改数据对象和选项的显示方式来适应不同的场景。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云