Ajax实现模拟关键字智能匹配搜索效果
程序员文章站
2024-01-17 13:59:46
准备数据keyword.json:(这里只贴出部分数据)
[
{"id":1,"initial":"ad","keyword":"奥迪"},
{"id...
准备数据keyword.json:(这里只贴出部分数据)
[ {"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结构
<form class="fl search_form" action="#" method="post"> <input class="search_text" id="searchkey" type="search" placeholder="请输入搜索关键字" onkeyup="searchsuggest(this);"/> <input class="search_btn" type="submit" value="搜索"/> </form> <!--start--智能搜索关键字匹配弹出层--> <ul class="keywords_list"></ul> <!--end--智能搜索关键字匹配弹出层-->
js:
//当在搜索框输入内容时,根据关键字匹配,显示弹出层 function searchsuggest(obj){ var searchkey=$(obj).val(); var reg = new regexp(searchkey,"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(); } }); } //单击匹配列表中的关键字选项时,将该关键字显示在搜索框中 function changesearchkey(obj){ var value=$(obj).text(); $("#searchkey").val(value); $('.keywords_list').hide(); }
效果图:
以上所述是小编给大家介绍的ajax实现模拟关键字智能匹配搜索效果,希望对大家有所帮助