html : ( autocomplete=“off” 禁止了浏览器自动补全行为 ,否则会与我们自己写的冲突)
<div class="search">
<input type="input" class="form-control" id="key" name="key" value="{key}" placeholder="请输入关键词" autocomplete="off">
<div id="auto_div"></div>
</div>
style:
.search
{
left: 0;
position: relative;
}
#auto_div
{
display: none;
width: 300px;
border: 1px #74c0f9 solid;
background: #FFF;
position: absolute;
color: #323232;
z-index: 999;
}
jq:
<script type="text/javascript">
$(function(){
$('#key').keyup(function(){ //当松开键盘键时发送ajax获取匹配数据
var keywords = $(this).val();
if (keywords=='') { $('#auto_div').hide(); return };
$.ajax({
url: '.....&keyword=' + keyword,
beforeSend:function(){ },
success:function(data){
console.log(data);
$('#auto_div').empty().show();
if (data != "") {
var res = JSON.parse(data);
$.each(res, function(){
$('#auto_div').append('<div class="word">'+ this +'</div>');
})
}
},
error:function(){ }
})
})
//点击数据复制到搜索框
$(document).on('click','.word',function(){
var word = $(this).text();
$('#key').val(word);
$('#auto_div').hide();
// $('#btn').trigger('click');触发搜索事件
})
//点击页面隐藏自动补全提示框
document.onclick = function (e) {
var e = e ? e : window.event;
var tar = e.srcElement || e.target;
if (tar.id != key) {
if ($('#auto_div').is(":visible")) {
$('#auto_div').css("display", "none")
}
}
}
})
</script>