今天为大家分享js实现模糊查询的功能!
(如果解决了您的问题,请帮忙给我点个赞吧,谢谢!!!)
话不多说直接上代码:(复制即可)
css部分:
<style>
.wrap{width:50%;margin:0 auto;}
#searchShow{font-size:12px;border:1px solid #ccc; margin-top:20px;}
#searchShow li{border:1px solid #ccc;padding:4px 5px;}
#searchShow li:nth-child(even) {
background: hsl(180, 35%, 58%);
color: #fff;
}
#searchShow li:nth-child(odd) {
background: White;
}
</style>
js部分:(需要引入jq库)
<script>
let listData = ["上海市","黄浦区","卢湾区","徐汇区","长宁区","静安区","普陀区",
"闸北区","杨浦区","虹口区","闵行区","宝山区","嘉定区","浦东新区",
"金山区","松江区","青浦区","南汇区","奉贤区","崇明县",];
renderTab(listData);//渲染表格
//键入触发事件
$('#searchKey').bind('input propertychange', function() {
//进行相关操作
var searchResult = fuzzySearch();
renderTab(searchResult);
});
//点击查询按钮触发事件
$('#searchBtn').click(function(){
var searchResult = fuzzySearch();
renderTab(searchResult);
});
// 正则表达式实现模糊查询
function fuzzySearch(){
var keyWord = $('#searchKey').val();
var len = listData.length;
var arr = [];
var reg = new RegExp(keyWord);
for(var i=0;i<len;i++){
//如果字符串中不包含目标字符会返回-1
if(listData[i].match(reg)){
arr.push(listData[i]);
}
}
return arr;
}
//渲染表格
function renderTab(list){
if(list.length==0){
$('#searchShow').html('未查询到关键字相关结果');
return;
}
var colStr = '';
for(var i=0,len=list.length;i<len;i++){
colStr+="<li>"+list[i]+"</li>";
}
$('#searchShow').html(colStr);
}
</script>
html部分:
<div class="wrap" id="wrap">
<input type='text' value="" id='searchKey'/>
<input type='button' value="查询" id='searchBtn'/>
<ul id='searchShow'></ul>
</div>