Home >Web Front-end >JS Tutorial >Detailed explanation of fuzzy query examples using js
This article mainly shares with you detailed examples of jjs implementation of fuzzy query. It is mainly shared with you in the form of code. I hope it can help you.
1. Brief description
There are many ways to implement fuzzy query. It can be implemented on the back end, and it can also be implemented using js on the front end.
To implement the backend, you need to splice SQL statement queries in the background based on the keywords searched in the input box.
The front-end directly uses the indexOf() method of strings or regular expression matching implementation. Compared with the back-end implementation of this method, the user experience is more friendly.
2, demo
When you enter content in the input box or click the query button,
Fuzzy query is performed based on the keywords in the input box the contents of the table and re-renders the table.
code show as below.
(1) javascript code:
let listData = ["Shanghai City", "Huangpu District", "Luwan District", "Xuhui District", "Changning District", "Jing'an District", "Putuo District",
"Zhabei District", "Yangpu District", "Hongkou District", "Minhang District", "Baoshan District", "Jiading District", "Pudong New District",
"Jinshan District", "Songjiang District", "Qingpu District", "Nanhui District", "Fengxian District", "Chongming County" ];
function Fuzzysearch(listData){ this.listData = listData,//请求得到的数据 this.searchKey = document.getElementById('searchKey'),//查询关键字 this.searchBtn = document.getElementById('searchBtn'),//查询按钮 this.searchShow = document.getElementById('searchShow')//显示查询结果的表格 this.renderTab(this.listData); this.init(); } Fuzzysearch.prototype={ init :function(){ let _this = this; //键入触发事件 _this.searchKey.onkeyup=function(){ let searchResult = _this.searchFn(); _this.renderTab(searchResult); }; //点击查询按钮触发事件 _this.searchBtn.onclick=function(){ let searchResult = _this.searchFn(); _this.renderTab(searchResult); }; }, searchFn:function(){ var keyWord = this.searchKey.value; var len = this.listData.length; var arr = []; var reg = new RegExp(keyWord); for(var i=0;i<len;i++){ //如果字符串中不包含目标字符会返回-1 if(this.listData[i].match(reg)){ arr.push(listData[i]); } } return arr; } ,renderTab:function(list){ let colStr = ''; if(list.length==0){ this.searchShow.innerHTML='未查询到关键字相关结果'; return; } for(var i=0,len=list.length;i<len;i++){ colStr+="<tr><td>"+list[i]+"</td></tr>"; } this.searchShow.innerHTML = colStr; } } new Fuzzysearch(listData);
Related recommendations:
Detailed example of how to implement fuzzy query in js
The above is the detailed content of Detailed explanation of fuzzy query examples using js. For more information, please follow other related articles on the PHP Chinese website!