前端jQuery和原生js 实现下拉框select模糊搜索功能总结
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select Fuzzy Search</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.3/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.3/dist/js/select2.min.js"></script>
</head>
<body>
<select id="mySelect" style="width: 200px;">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
<option value="pineapple">Pineapple</option>
<option value="strawberry">Strawberry</option>
<option value="mango">Mango</option>
</select>
<script>
$(document).ready(function() {
$('#mySelect').select2({
placeholder: 'Search Fruit',
allowClear: true
});
});
</script>
</body>
</html>
这段代码使用了Select2库来为普通的<select>
元素添加模糊搜索功能。在页面加载完成后,Select2会自动初始化这个下拉框,并且允许用户通过输入来过滤选项。这是一个简单而实用的下拉框模糊搜索实现,适用于各种前端开发场景。
评论已关闭