有时,项目中一个页面需要有多个自动提示功能,本文使用最新jquery-ui(1.12)演示了实现过程。
一、参考地址
https://jqueryui.com/autocomplete/#custom-data
二、实现步骤
直接上代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>jQuery-ui自动提示</title>
<!-- 引入jQuery UI的css文件 -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="external nofollow" >
<!-- 引入jQuery的js文件 -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.3.js" ></script>
<!-- 引入jQuery UI的js文件 -->
<script type="text/javascript" src="http://code.jquery.com/ui/1.12.1/jquery-ui.js" ></script>
</head>
<body>
<label>请输入:</lable><br></label>
第一行:<input id="inputName1" name="language" type="text" onfocus="myHint('inputName1')">
<br>
第二行:<input id="inputName2" name="language" type="text" onfocus="myHint('inputName2')">
<br>
第三行:<input id="inputName3" name="language" type="text" onfocus="myHint('inputName3')">
<br>
<br>
<div id="showMsg"></div>
</body>
<script type="text/javascript">
var projects = [
{ value: "zhangsan", label: "张三" },
{ value: "lisi", label: "李四" },
{ value: "wangwu", label: "王五" },
{ value: "zhangemazi", label: "张二麻子"},
{ value: "zhangshanfeng", label: "张三丰" },
{ value: "zhangerfeng", label: "张二丰" },
{ value: "lixiaoba", label: "李小八"}
];
$(document).ready(function( ){
myHint=function(hintId){
$("#"+hintId).autocomplete( {
source: function( request, response ) {
var results = $.ui.autocomplete.filter(projects, request.term);
response(results.slice(0, 3));//最多显示几条
},
messages:{
//不显示提示,不加的话会有英文提示
noResults:'',
results:function(){}
},
focus: function( event, ui ) {
$( "#"+hintId ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#"+hintId ).val( ui.item.label );
$( "#showMsg" ).text( "您选择了:"+ui.item.value );
return false;
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
//格式化
return $( "<li style='background-color: white;'>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
};
});
</script>
</html>