準(zhǔn)備數(shù)據(jù)keyword.json:(這里只貼出部分?jǐn)?shù)據(jù))
[ {"id":1,"initial":"ad","keyword":"奧迪"}, {"id":2,"initial":"ada4l","keyword":"奧迪A4L"}, {"id":3,"initial":"ada6l","keyword":"奧迪A6L"}, {"id":4,"initial":"adq5","keyword":"奧迪Q5"}, {"id":5,"initial":"ada3","keyword":"奧迪A3"}, {"id":6,"initial":"adq7","keyword":"奧迪Q7(進口)"}, {"id":7,"initial":"ada8","keyword":"奧迪A8L(進口)"}, {"id":8,"initial":"bm","keyword":"寶馬"}, {"id":9,"initial":"bm5x","keyword":"寶馬5系"}, {"id":10,"initial":"bm7x","keyword":"寶馬7系"}, {"id":11,"initial":"bt","keyword":"本田"}, {"id":12,"initial":"bqsbx25","keyword":"北汽紳寶 X25"}, {"id":13,"initial":"bqsbx35","keyword":"北汽紳寶X35"}, {"id":14,"initial":"bqsbx55","keyword":"北汽紳寶X55"} ]
html結(jié)構(gòu)
<form class="fl search_form" action="#" method="post"> <input class="search_text" id="searchKey" type="search" placeholder="請輸入搜索關(guān)鍵字" onkeyup="searchSuggest(this);"/> <input class="search_btn" type="submit" value="搜索"/> </form> <!--start--智能搜索關(guān)鍵字匹配彈出層--> <ul class="keywords_list"></ul> <!--end--智能搜索關(guān)鍵字匹配彈出層-->
js:
//當(dāng)在搜索框輸入內(nèi)容時,根據(jù)關(guān)鍵字匹配,顯示彈出層 function searchSuggest(obj){ var searchKey=$(obj).val(); var reg = new RegExp(searchKey,"i"); //忽略大小寫匹配搜索框中輸入的內(nèi)容 $.ajax({ type:"get", url:"data/keyword.json", dataType:"json", success:function(data){ var arr=[]; for(var i=0,len=data.length;i<len;i++){ if(searchKey!="" && (data[i].initial.search(reg)!=-1 || data[i].keyword.search(reg)!=-1)) { arr.push("<li onclick='changeSearchKey(this);'>"+data[i].keyword+"</li>"); } } $(".keywords_list").html(arr).show(); } }); } //單擊匹配列表中的關(guān)鍵字選項時,將該關(guān)鍵字顯示在搜索框中 function changeSearchKey(obj){ var value=$(obj).text(); $("#searchKey").val(value); $('.keywords_list').hide(); }
效果圖:
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
在Lavarel框架中ajax需要怎么提交表單
Ajax實現(xiàn)加載進度條的步奏詳解
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com