使用Autocomplete可以很簡單的就有文本框的自動補全功能提示了。
在HTML文件中引入autocomplete的js文件和css樣式文件,以及autocomplete壓縮包中的jQuery的js文件,不要私自用高版本的jQuery,可能會導致顯示不出效果。
先來從網友那裏拷貝過來的最簡單的例子:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>autocomplete</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
var websites = [
"Google", "NetEase", "Sohu", "Sina", "Sogou", "Baidu", "Tencent",
"Taobao", "Tom", "Yahoo", "JavaEye", "Csdn", "Alipay"
];
$().ready(function () {
$("#website").autocomplete(websites);
});
</script>
</head>
<body>
<p>
<label>Web Site:</label>
<input type="text" id="website"/>
<input type="button" id="getvalue" value="Get Value"/>
</p>
<div id="content"></div>
</body>
</html>
出來的效果如下:
缺點就是隻能匹配前面的,不能匹配中間的,不知有沒有相關的配置修改,且接着學下去再看看。
仔細的研究一下autocomplete( url or data, [options] )方法。
autocomplete方法有兩個參數,第一個用來填寫URL地址或是數據,jQuery Autocomplete插件是支持Ajax方式調用數據,所以可以填寫調用的地址,另外可以直接填寫數據,格式爲JavaScript數組,如我們的例子,autocomplete的另外一個參數 [options]是一個可選項,我們在例子中就沒有寫,但這個參數裏面卻有很多可配置的參數,我們還是先修改上面的例子。
$().ready(function () {
$("#website").autocomplete(websites, {
minChars: 0,
max: 5,
autoFill: true,
mustMatch: true,
matchContains: true,
scrollHeight: 220,
formatItem: function (data, i, total) {
return "<I>" + data[0] + "</I>";
}, formatMatch: function (data, i, total) {
return data[0];
}, formatResult: function (data) {
return data[0];
}
});
});
在options項我們增加了好幾個參數
minChars表示在自動完成激活之前填入的最小字符,這裏我們設置爲0,在我們雙擊文本框,不輸入字符的時候,就會把數據顯示出來,效果如下:
max表示列表裏的條目數,我們設置了5,所以顯示5條,也如上圖
autoFill表示自動填充,就是在文本框中自動填充符合條件的項目,看下圖,在我們輸入“g”的時候,文本框裏填充了“google”。
mustMatch表示必須匹配條目,也就是在文本框裏輸入的內容,必須是data參數裏的數據,如果不匹配,文本框就被清空
matchContains表示包含匹配,就是data參數裏的數據,是否只要包含文本框裏的數據就顯示,比如在上面的圖中,我們輸入了“g”,由於“Sogou”中也包含一個“g”,所以會顯示出來,如果將matchContains設爲fasle,則“Sogou”就不會顯示
scrollHeight不用多解釋,看文檔就知道。
後面3個參數formatItem、formatMatch、formatResult非常有用,formatItem作用在於可以格式化列表中的條目,比如我們加了“I”,讓列表裏的字顯示出了斜體,formatMatch是配合formatItem使用,作用在於,由於使用了formatItem,所以條目中的內容有所改變,而我們要匹配的是原始的數據,所以用formatMatch做一個調整,使之匹配原始數據,formatResult是定義最終返回的數據,比如我們還是要返回原始數據,而不是formatItem過的數據。
[options]裏還有很多有用的參數,大家可以看它的文檔。
本地json數據的自動補全:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>autocomplete</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
var names = [
{name:'li',age:23},
{name:'huang',age:26},
{name:'goof',age:45},
{name:'link',age:67}
];
$().ready(function() {
$("#website").autocomplete(names,{
minChars: 1,
max: 5,
autoFill: true,
mustMatch: true,
matchContains: true,
scrollHeight: 220,
formatItem: function(data, i, total) {
return "<I>"+data.name+"</I>" + data.age;
},
formatMatch: function(data, i, total) {
return data.name;
},
formatResult: function(data) {
return data.name;
}
});
});
</script>
</head>
<body>
<p>
<label>Web Site:</label>
<input type="text" id="website"/>
<input type="button" id="getvalue" value="Get Value"/>
</p>
<div id="content"></div>
</body>
</html>
==================================================================
調用服務器端json數據,服務端用servlet來實現,json數據用fastjson來生成。上maven倉庫下載fastjson這個jar包,當然生成json語句的jar不少,也可以用其他的。
編寫一個轉換爲json的工具類:\src\com\lifeix\util\FastJsonUtil.java
這個類非常簡單,如下:
package com.lifeix.util;
import com.alibaba.fastjson.JSON;
/**
* Created by lhx on 14-12-10 下午4:15
*
* @project jspProject
* @package com.lifeix.util
* @blog http://blog.csdn.net/u011439289
* @email [email protected]
* @Description
*/
public class FastJsonUtil {
/**
* Object實體轉換爲json
* @param object
* @return
*/
public static String object2json(Object object){
JSON json = (JSON) JSON.toJSON(object);
return json.toJSONString();
}
}
編寫一個servlet:src\com\lifeix\servlet\JsonServlet.java,主要是輸出json數據給前臺。
package com.lifeix.servlet;
import com.lifeix.util.FastJsonUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by lhx on 14-12-9 下午4:19
*
* @project jspProject
* @package ${PACKAGE_NAME}
* @blog http://blog.csdn.net/u011439289
* @email [email protected]
* @Description
*/
public class JsonServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = null;
try {
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
pw = response.getWriter();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String,String> map = new HashMap<String, String>();
map.put("name","Link");
map.put("num", "34");
list.add(map);
map = new HashMap<String, String>();
map.put("name","Li");
map.put("num", "123");
map = new HashMap<String, String>();
map.put("name","Tom");
map.put("num", "76");
list.add(map);
map = new HashMap<String, String>();
map.put("name","Gnk");
map.put("num","583");
list.add(map);
String jsonstr = FastJsonUtil.object2json(list);
pw.print(jsonstr);
pw.flush();
}catch (Exception e) {
e.printStackTrace();
}
finally {
if (pw != null)
pw.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
編寫前臺JavaScript代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>autocomplete</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<!--<script src="js/emails.js" type="text/javascript"></script>-->
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
var names ;
$(document).ready(function(){
$.ajax({
type:'POST',
contentType: "application/json",
url: "/jsonservlet",
dataType: "json",
success:function(data){
names = data;
autocompleteFn(data);
}
});
});
function autocompleteFn(names){
$("#website").autocomplete(names,{
minChars: 0,
max: 5,
dataType:"json",
autoFill: true,
mustMatch: true,
matchContains: true,
scrollHeight: 220,
formatItem: function(data, i, total) {
return "<I>"+data.name+"</I>" + " <font style='color: #009933; font-family: 黑體; font-style: italic'>次數:" + data.num + "</font>";
},
formatMatch: function(data, i, total) {
return data.name;
},
formatResult: function(data) {
return data.name;
}
});
}
</script>
</head>
<body>
<p>
<label>Web Site:</label>
<input type="text" id="website"/>
<input type="button" id="getvalue" value="Get Value"/>
</p>
<div id="content"></div>
</body>
</html>
這代碼很容易理解,先用jQuery的ajax技術在頁面加載的時候就從後臺獲取數據,緩存到names中,接着調用autocompletefn函數,把數據傳到這個函數中,再調用autocomplete這個插件,頁面在輸入的時候就會有自動補全的功能了。
最後的效果爲:
========================================================
單獨的Autocomplete項目已經取消更新了,取而代之的是jQuery UI社區的Autocomplete,地址爲:http://jqueryui.com/autocomplete/
在這個網頁上,有個例子也非常簡單,它能匹配中間的字符,特效也好點。我們可以直接拷貝代碼放到自己的機器上運行,不過因爲引用的js和css文件都是要聯網下載的,所以要保證你的機器的在聯網情況下纔可以。
代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
後記:
本地調用json數據的時候,纔想console出返回的數據,把formatItem、 formatMatch和formatResult這三個函數都捨去了return。結果就出現了以下的錯誤,害得我找了很久都不知什麼原因。
最後發現是中間的formatMatch函數是不能捨去return語句的: