類似百度的搜尋下拉(僅前端)
阿新 • • 發佈:2021-09-15
做一個類似百度下拉框的搜尋下拉。
例如:輸入“騰”字,下拉框顯示模糊查詢的所有結果。
先看一下效果:
html中簡單寫一個輸入框,寫一個<ul>放內容:
1 <div style="margin-left:10px;margin-right:10px;padding-left:50px;padding-top:10px;padding-bottom:1px;text-align:center;border-radius:12px;background:url('/public/images/4.png') no-repeat"> 2 <input id="calcountput"autocomplete="off" type="text" style="border:2pxsolid#9DC3C1;margin-top:-10px;border-radius:10px;" name="title" required placeholder="請輸入使用者名稱稱" class="layui-input"> 3 <ul id="list"></ul> 4 </div>
js部分程式碼,用input來監聽輸入的動作,最好判斷一下是不是英文/拼音。
每一次輸入內容改變,都呼叫一次介面,將關鍵字傳到後臺,後臺將模糊查詢的結果傳回前端。
拿到的資料放入<li>,for迴圈,有幾條就新建幾條<li>。
1 $('#calcountput').on('input',function(){ 2 var inputkey = $('#calcountput').val(); 3 if(inputkey == null || inputkey == ''){ 4 $('#list').html(''); 5 }else{ 6 if(/^[\u4e00-\u9fa5]+$/i.test(inputkey)){//判斷不能是英文 7 console.log(inputkey);8 axios.post(url,{userName:inputkey} ) 9 .then(function (response) { 10 console.log(response.data['data']); 11 let res = response.data['data']; 12 $('#list').html(''); 13 for(let i in res){ 14 $(`<li style="cursor: pointer;" uservpn="${res[i]['user_vpnnum']}" userabbr="${res[i]['user_abbreviation']}">${res[i]['user_componyname']}</li>`).appendTo("#list"); 15 } 16 $('ul li').on('click',function(){ 17 //點選事件,根據自己專案的需求寫就行 18 }) 19 }) 20 .catch(function (error) { 21 console.log(error); 22 }); 23 } 24 } 25 26 })
2021-09-1515:51:04