写一个js都下拉菜单二级联动
时间: 2024-05-15 20:19:58 浏览: 14
我可以回答这个问题。下拉菜单的二级联动可以通过以下步骤实现:
1. 在 HTML 中创建两个 select 元素,一个用于选择一级选项,一个用于选择二级选项。
2. 给第一个 select 元素添加 onchange 事件,在事件处理函数中获取到选中的一级选项的值。
3. 根据一级选项的值,动态生成二级选项的内容,并更新第二个 select 元素的选项。
4. 给第二个 select 元素添加 onchange 事件,在事件处理函数中获取到选中的二级选项的值。
以下是一个简单的实现代码示例:
HTML 代码:
```
<select id="first">
<option value="option1">选项1</option>
<option value="option2">选项2</option>
</select>
<select id="second"></select>
```
JavaScript 代码:
```
const first = document.getElementById('first');
const second = document.getElementById('second');
const options = {
option1: ['子选项1', '子选项2', '子选项3'],
option2: ['子选项4', '子选项5', '子选项6'],
};
first.addEventListener('change', () => {
const selected = first.value;
const subOptions = options[selected];
let html = '';
for (const option of subOptions) {
html += `<option value="${option}">${option}</option>`;
}
second.innerHTML = html;
});
second.addEventListener('change', () => {
const selected = second.value;
console.log(`选择了 ${selected}`);
});
```