html+js+select只有一个下拉选择,点开下拉实现多层级选择的代码
时间: 2024-05-05 11:20:09 浏览: 12
以下是一个简单的实现:
HTML:
```html
<select id="select1" onchange="changeSelect(this)">
<option value="">请选择</option>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
<option value="4">选项4</option>
</select>
```
JS:
```js
var data = [
{
label: '选项1',
value: '1',
children: [
{
label: '选项1-1',
value: '1-1'
},
{
label: '选项1-2',
value: '1-2'
}
]
},
{
label: '选项2',
value: '2',
children: [
{
label: '选项2-1',
value: '2-1'
},
{
label: '选项2-2',
value: '2-2',
children: [
{
label: '选项2-2-1',
value: '2-2-1'
},
{
label: '选项2-2-2',
value: '2-2-2'
}
]
}
]
},
{
label: '选项3',
value: '3',
children: [
{
label: '选项3-1',
value: '3-1'
},
{
label: '选项3-2',
value: '3-2'
}
]
},
{
label: '选项4',
value: '4',
children: [
{
label: '选项4-1',
value: '4-1'
},
{
label: '选项4-2',
value: '4-2'
}
]
}
];
function changeSelect(select) {
// 获取选中值
var selectedValue = select.value;
// 获取下一级select元素
var nextSelect = select.nextElementSibling;
// 隐藏其他下一级select
while (nextSelect) {
nextSelect.style.display = 'none';
nextSelect = nextSelect.nextElementSibling;
}
// 如果选中值不为空,则显示下一级select并填充选项
if (selectedValue) {
// 在下一级select元素不存在的情况下,创建一个
if (!nextSelect) {
nextSelect = document.createElement('select');
nextSelect.onchange = function() {
changeSelect(this);
};
select.parentElement.appendChild(nextSelect);
}
nextSelect.style.display = 'inline-block';
nextSelect.innerHTML = '<option value="">请选择</option>';
var options = data.find(function(item) {
return item.value === selectedValue;
}).children;
options.forEach(function(item) {
var option = document.createElement('option');
option.value = item.value;
option.innerHTML = item.label;
nextSelect.appendChild(option);
});
}
}
```
这个代码实现了一个选择多层级选项的功能,当用户在select元素中选择一个选项时,下一个select元素会在同级中被添加,用户可以接着在其中选择另一个选项。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)