1、插件引入
引用,插件下载
<link rel="stylesheet" href="${commonStatic}/common/jquery/css/autocomplete.min.css">
<script src="${commonStatic}/common/jquery/ui/autocomplete.min.js"></script>
不要使用
<link rel="stylesheet" href="${webStatic}/common/plugins/jquery-ui-1.12.1/jquery-ui.min.css">
<script src="${webStatic}/common/plugins/jquery-ui-1.12.1/jquery-ui.min.js"></script>
后者可能会出现样式问题
2、代码
$("#searchOeInput").autocomplete({
minLength: 0,
source: function(request,response){
if(request.term.length == 0){
//查历史搜索记录
$.ajax({
type: 'post',
url: '/portal/querySearchHistory',
data:{'searchKeyword':request.term,'searchType':'epc','count':10},
dataType: 'json',
success:function(data){
var keywordOjects = data.keywordList,
result = [];
if(keywordOjects){
for(var i=0; i<keywordOjects.length; i++) {
result.push(keywordOjects[i].searchKeyword);
}
response(result);//展现数据
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
}else{
//查联想词
$.ajax({
type: 'get',
url: '/maindata/restApi/v1/oe/oeStandardNames',
data:{'oeName':request.term,'vin':vin},
dataType: 'json',
success:function(result){
if(result && result.data){
response(result.data);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
}
},
select: function( event, ui){//从下拉列表中选择后触发
//判断返回数据是历史记录还是联想词
if(ui.item.hasOwnProperty('standard')){
$(this).blur();
searchEpcParts(ui.item.value);
}else{
event.preventDefault();//阻止默认动作(value值填充到input中)
$(this).val(ui.item.value).trigger('input');//input中内容改变时触发事件
}
}
}).focus(function() {//结合minLength: 0,focus时就触发事件
$(this).autocomplete("search", $(this).val());
}).data("ui-autocomplete")._renderItem = function(ul, item) {//_renderItem用于自定义下拉框样式
//区分搜索历史记录和联想词
if(item && item.hasOwnProperty('standard')){
var html = '<a><span style="float:left;">' + item.alias + '</span><span style="float:right;font-weight:bold;">' + item.standard + '</span></a>';
item.value = item.standard;
return $("<li>").data("item.autocomplete", item)
.append(html)
.appendTo(ul);
}
return $("<li>").data("item.autocomplete", item)
.append(item.value)
.appendTo(ul);
};