js实现select
实现基本的HTML下拉选择框
使用HTML的<select>元素可以创建基本的下拉选择框,JavaScript用于增强交互性。
<select id="mySelect">
<option value="option1">选项1</option>
<option value="option2">选项2</option>
<option value="option3">选项3</option>
</select>
动态添加选项
通过JavaScript动态添加选项到select元素。
const select = document.getElementById('mySelect');
const newOption = document.createElement('option');
newOption.value = 'option4';
newOption.text = '选项4';
select.add(newOption);
获取选中值
使用JavaScript获取用户选择的选项值。

const select = document.getElementById('mySelect');
select.addEventListener('change', function() {
const selectedValue = this.value;
console.log('选中的值:', selectedValue);
});
自定义样式下拉框
使用CSS和JavaScript创建自定义样式的下拉框。
<div class="custom-select">
<div class="select-selected">选项1</div>
<div class="select-items">
<div>选项1</div>
<div>选项2</div>
<div>选项3</div>
</div>
</div>
document.querySelectorAll('.custom-select .select-selected').forEach(select => {
select.addEventListener('click', function() {
this.nextElementSibling.classList.toggle('select-hide');
});
});
document.querySelectorAll('.custom-select .select-items div').forEach(item => {
item.addEventListener('click', function() {
const selected = this.parentNode.previousElementSibling;
selected.textContent = this.textContent;
this.parentNode.classList.add('select-hide');
});
});
使用第三方库实现高级选择框
考虑使用Select2等第三方库实现更丰富的功能。

<select class="js-example-basic-single" style="width: 100%">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
多选下拉框实现
HTML5原生支持多选下拉框。
<select id="multiSelect" multiple>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
</select>
const multiSelect = document.getElementById('multiSelect');
multiSelect.addEventListener('change', function() {
const selectedOptions = [...this.selectedOptions].map(option => option.value);
console.log('选中的多个值:', selectedOptions);
});
搜索过滤功能
为下拉框添加搜索过滤功能。
function filterFunction(inputId, selectId) {
const input = document.getElementById(inputId);
const filter = input.value.toUpperCase();
const select = document.getElementById(selectId);
const options = select.getElementsByTagName('option');
for (let i = 0; i < options.length; i++) {
const txtValue = options[i].textContent || options[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
options[i].style.display = "";
} else {
options[i].style.display = "none";
}
}
}





