<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<title></title>
<style>
.mockselect input {
width: 100%;
height: 40px;
user-select: none;
outline: none;
box-sizing: border-box;
padding: 0 8px;
}
.mockselect ul {
position: relative;
width: 99%;
height: auto;
border: 1px solid #66afe9;
border-top: 0px;
overflow: auto;
display: none;
list-style-type: none;
}
.mockselect ul li {
width: 100%;
height: 40px;
margin-top: 1px;
font-size: 13px;
line-height: 40px;
box-sizing: border-box;
padding: 0 8px;
}
.mockselect ul li:hover{
background-color: #1C86EE;
color: #fff;
}
</style>
</head>
<body>
<div class="mockselect">
<!--要模糊匹配的文本框-->
<input type="text"/>
<!--模糊匹配窗口-->
<ul></ul>
</div>
</body>
</html>
<script type="text/javascript">
function mockselect(y){
var a = $(y).find("input"); //a为输入框列表
var b = $(y).find("ul"); //b为检索列表
var isClick = true;
//隐藏搜索结果列表框
$("body").click(function () {
b.hide();
});
//弹出搜索结果列表框
a.click(function (e) {
if(a.val().length <= 0){
b.hide();
}else{
b.show();
}
e.stopPropagation();
});
//点击选择当前标签
b.on("click", "li", function () {
a.val( $(this).text() );
});
//文本框输入开始检索
a.keyup(function(){
if(isClick){
isClick = false;
setTimeout(function() {
isClick = true;
var contentval = a.val(); //检索内容
select(contentval);
}, 1000);// 1秒内不能重复点击
}
});
function select(contentval){
if (a.val().length <= 0) {
b.empty();
b.hide();
}else{
$.ajax({
type:"GET",
url:"tsconfig.json",
data: {
"contentval": contentval //向后台返回用户输入内容并检索
},
success:function(data){
b.empty();
if(data){
var arr = data.namelist; //后台数据
//前台检索并返回数据
// var value = a.val(); //输入内容
// $.each(arr,function (index,val) {
// if( val.name.indexOf(value) > -1 || val.spell.indexOf(value) > -1){
// b.append("<li class='mockselect_item_"+ index +"'>"+ val.name +"</li>");
// console.log(val.name.substr(0, val.name.length))
// }
// });
//后台检索并返回数据
$.each(arr,function (index,val) {
b.append("<li class='mockselect_item_"+ index +"'>"+ val.name +"</li>");
});
b.show(); //展示模糊匹配窗口
}else{
console.log("暂无数据")
}
},
error:function(jqXHR){
console.log("数据异常")
}
})
}
};
}
mockselect('.mockselect'); //最外层div的名字
</script>
模拟搜索输入框 可复用 前台判断和后台判断都有 最后调用方法即可 (后台判断反而前台代码更少些 只需要把后台返回的数据动态显示到li标签中 )