核心是 oninput 输入时触发事件
核心代码如下
<input id=\"name\" oninput=\"search()\" type=\"text\"><span class=\"clear\" onclick=\"delInput()\">×</span><div class=\"select-form\"><dl></dl></div>
//避免重复请求var searchFlag = truevar list = []function search(){if($(\'#name\').val() && searchFlag){searchFlag = false$(\'dl\').html(\'\')$.ajax({url: \'xxx\',type : \'post\',data: {name: $(\'#name\').val()},success: (res)=>{if(res){list = eval(\'(\' + res + \')\')if(list.length > 0){list.forEach((item, index, input)=>{$(\'dl\').append(\'<dd οnclick=\"select(\\\'\'+item.id+\'\\\')\">\'+item.name+\'</dd>\')$(\'.select-form\').css(\'display\', \'block\')})}else{$(\'.err\').css(\'display\', \'block\')}}searchFlag = true}})}else{list = []}}function delInput(){$(\'#name\').val(\'\')$(\'dl\').html(\'\')$(\'.select-form\').css(\'display\', \'none\')list = []selObj = {}}
.select-form{display: none;}
再调调样式,小功告成
效果图: