前言:最近做的一个项目,需要做一个类似百度输入框自动提醒的效果,在几经研究之后,我决定使用Jquery UI中的Autocomplete来实现这一功能。
先看效果
参考地址:demo
参考地址:详解API
下载jquery UI控件
下载地址:http://jqueryui.com/download/
前端页面代码
<input type="text" id="parameter" placeholder="请输入相关信息"/>
js代码
$(document).ready(function(){
$( "#parameter" ).autocomplete({
source:function(request, response){
$.ajax( {
url: "${pageContext.request.contextPath}/country/showCountry.do",
dataType: "json",
data: {
"parameter" :request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.country_code+" "+item.english_name+" "+item.chinese_name,
value: item.country_code
}
}));
},
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
} );
}
});
});
引用的资源
<link rel="stylesheet" href="${pageContext.request.contextPath}/resource/css/jquery_UI/jquery-ui.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/resource/css/jquery_UI/style.css">
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="${pageContext.request.contextPath}/resource/js/jquery_UI/jquery-ui.js"></script>
控制层代码
@RequestMapping("showCountry")
@ResponseBody
public List<Country> showCountry(String parameter){
//避免查太多,这里指定了数量 或者是添加在js中添加 minLength属性
int start=0;
int length=10;
List<Country> countrys=service.selectCountryBypage2(start, length, parameter);
return countrys;
}
ps: Autocomplete还可以有更多的应用,这里只是举了一个较为简单例子,欢迎大家评判指正!!