类似百度的搜索下拉(仅前端)

做一个类似百度下拉框的搜索下拉。

例如:输入“腾”字,下拉框显示模糊查询的所有结果。

先看一下效果:

 

 

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:2px solid #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

posted @ 2021-09-15 15:52  silvia喵  阅读(358)  评论(0)    收藏  举报