js实现select
实现 JavaScript 的 select 功能
原生 JavaScript 实现
使用 document.createElement 创建 select 元素并添加 option 子元素:
const select = document.createElement('select');
select.id = 'mySelect';
const option1 = document.createElement('option');
option1.value = 'value1';
option1.textContent = 'Option 1';
const option2 = document.createElement('option');
option2.value = 'value2';
option2.textContent = 'Option 2';
select.appendChild(option1);
select.appendChild(option2);
document.body.appendChild(select);
动态填充选项
通过数组动态生成 option 并添加到 select 中:
const fruits = ['Apple', 'Banana', 'Orange'];
const select = document.createElement('select');
fruits.forEach(fruit => {
const option = document.createElement('option');
option.value = fruit.toLowerCase();
option.textContent = fruit;
select.appendChild(option);
});
document.body.appendChild(select);
获取选中值
监听 change 事件获取用户选择的选项值:
const select = document.getElementById('mySelect');
select.addEventListener('change', function() {
console.log('Selected value:', this.value);
console.log('Selected text:', this.options[this.selectedIndex].text);
});
设置默认选中项
通过设置 selectedIndex 或 selected 属性指定默认选项:
const select = document.getElementById('mySelect');
select.selectedIndex = 1; // 选中第二个选项
// 或者
const options = select.options;
options[2].selected = true; // 选中第三个选项
禁用 select 元素
通过设置 disabled 属性禁用整个下拉列表:
document.getElementById('mySelect').disabled = true;
多选 select 实现
添加 multiple 属性允许选择多个选项:
const select = document.createElement('select');
select.multiple = true;
select.size = 4; // 设置可见行数
// 获取所有选中值
select.addEventListener('change', function() {
const selectedValues = Array.from(this.selectedOptions)
.map(option => option.value);
console.log('Selected values:', selectedValues);
});
清空所有选项
移除 select 中的所有 option 元素:
const select = document.getElementById('mySelect');
select.innerHTML = '';
// 或者
while (select.firstChild) {
select.removeChild(select.firstChild);
}
使用 HTML 字符串创建
通过 innerHTML 快速创建 select 结构:
const select = document.createElement('select');
select.innerHTML = `
<option value="">-- Please Select --</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
`;
document.body.appendChild(select);
样式化 select 元素
使用 CSS 自定义 select 的外观:

#mySelect {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
background-color: white;
font-size: 16px;
width: 200px;
}
#mySelect:focus {
outline: none;
border-color: #4CAF50;
}
兼容性注意事项
- 某些移动设备上
select的样式可能受限 - 使用
select时考虑添加label元素以提高可访问性 - 对于复杂需求可考虑使用第三方库如
Select2或react-select






