前端实现下拉模糊查询实例,只能选择存在的数据,不存在的数据不能选择也不能输入
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>面向对象(下拉框 与 模糊搜索)</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="./public/index.css">
</head>
<body >
<div class="box">
<h4>下拉模糊查询</h4>
<div class="dropdown custom1">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
<em>请选择</em>
<i class="caret"></i>
</button>
<ul class="dropdown-menu">
<li >
<input class="form-control seach_name" placeholder="请输入搜索内容"/>
<i class="glyphicon glyphicon-search"></i>
</li>
<li data="red"><a>red</a></li>
<li data="blue"><a>blue</a></li>
<li data="gray"><a>gray</a></li>
<li data="green"><a>green</a></li>
</ul>
</div>
</div>
<script src="./public/index.js"></script>
<script>
$(function(){
//new一个实例
new DropdownSearch('.custom1');
//new DropdownSearch('.custom2')
})
</script>
</body>
</html>
index.css
.box {
margin: 0px auto;
width: 500px;
margin-top: 70px;
}
* {
margin: 0;
padding: 0;
}
em {
font-style: normal;
}
.dropdown {
width: 300px;
}
.dropdown button {
width: 100%;
text-align: left;
border: solid 1px #e1e1e1;
background: #fff !important;
border-radius: 3px;
height: 32px;
}
.dropdown button i {
float: right;
margin-top: 8px;
}
.dropdown ul {
width: 100%;
}
.dropdown ul input {
height: 25px;
padding: 3px 10px;
border: 1px solid #ccc;
border-radius: 15px;
width: 100%;
}
.dropdown-menu li:first-child {
position: relative;
padding: 5px 10px;
}
.dropdown-menu li:first-child i {
position: absolute;
top: 12px;
right: 20px;
font-size: 10px;
}
index.js
//DropdownSearch 构造
function DropdownSearch(dropdown){
this.dropdown = dropdown;
var _this = this;
$(document).on('click',''+_this.dropdown+' .dropdown-menu a',function(e){
_this.select(e);
})
$(document).on('keyup',''+_this.dropdown+' .dropdown-menu .seach_name',function(e){
_this.search(e);
})
}
//选择方法 选中之后赋值到元素上
DropdownSearch.prototype.select = function(e){
var _text = $(e.target).text(),
parent = $(e.target).closest(this.dropdown);
$(parent).find("button em").html(_text);
}
//搜索方法 根据 li 上的data属性来进行搜索
DropdownSearch.prototype.search = function(e){
var value = $(e.target).val().trim();
if(value.length < 1){
$(''+this.dropdown+' li:not(":first")').show();
}else{
$(''+this.dropdown+' li:not(":first")').hide();
$(this.dropdown).find("li:not(':first')[data*='"+value+"']").show();
}
}