參考鏈接:https://blog.csdn.net/weixin_30920513/article/details/97463450
思路:1.先獲取搜索框的內容
2.第二步獲取要查詢的內容,注意寫到for循環里面(比如我是按照標題查詢,先寫for循環,逐一獲得標題內容,即查詢內容)
3.用mach()方法去匹配,不符合條件的加,display:none,隱藏掉該條數據
css:
#noFound{ color:#676a6c; text-align:center; padding:20px; display:none; }
html結構大致如下:
<div>
<input type="text" id="searchContent" placeholder="搜索任務"/>
<button id="search">搜索</button>
</div>
<div id="finished"> <ul> <li> <div class="panTitle"> 任務:<span>xxx項目開發</span> </div> <div> ... </div> </li>
<p id="noFound">沒有找到匹配的記錄</p> //一開始display 默認為none </ul> </div>
js:核心代碼已標紅
//搜索 function search(){ var searchContent = $("#searchContent").val();//獲取input輸入框值 var searchLen = $("#finished li").length;//獲取查詢條數,頁面li的數目 var searchAll = $("finished .planTitle span").text(); for (var i=0; i<searchLen;i++){ let searchText = $("#finished .panTitle span")[i].innerText;//獲取要查詢的內容,注意要寫到for循環里面 if(searchText.match(searchContent)){ $("#finished li")[i].style.display=''; }else{ $("#finished li")[i].style.display='none';//不符合查詢條件的當前數據隱藏 } } if(searchAll.match(searchContent)){ $("#noFound").css("display","none"); }else{ $("#noFound").css("display","block"); } } //搜索按鈕點擊時觸發 $("#search").on("click",function(){ search();//調用 }) //實現搜索內容隨着input輸入框實時查詢,監聽input輸入框搜索內容實現查詢 $("#searchContent").bind("input propertychange",function(){ search(); //調用搜索方法 })
代碼非常簡單,此時監聽搜索回車方法可以去掉了,因為監聽input輸入框搜索已經涵蓋了監聽回車事件的功能,
關於propertychange,propertychange 事件是實時觸發,即每增加或刪除一個字符就會觸發,更加詳細的了解參考小白點
博主的文章即時反應的input和propertychange方法
總結:本次查詢適用純前端頁面的模糊查詢,對於不需要后台數據返回的查詢,采用純前端查詢,有利於減少后端請求,提高性能
缺點:本次查詢只實現了連續查詢,例如查詢標題是:“前端頁面開發”,輸入“前端”,“開發”,任意連續字符可以查詢到該條數據,
但是輸入不連續字符如“前開”則查詢不到,后續仍需繼續優化,另外本頁面如有錯誤之處,歡迎評論區指正!