官網:http://jqueryui.com/autocomplete/
以下分享自:http://www.cnblogs.com/yuzhongwusan/archive/2012/06/04/2534262.html
jQuery UI Autocomplete是jQuery UI的自動完成組件,是我用過的最強大、最靈活的Autocomplete,它支持本地的Array/JSON數組、通過ajax請求的Array/JSON數組、JSONP、以及Function(最靈活)等方式來獲取數據。
支持的數據源
jQuery UI Autocomplete主要支持字符串Array、JSON兩種數據格式。
普通的Array格式沒有什么特殊的,如下:
1
|
[
"cnblogs"
,
"博客園"
,
"囧月"
]
|
對於JSON格式的Array,則要求有:label、value屬性,如下:
其中label屬性用於顯示在autocomplete彈出菜單,而value屬性則是選中后給文本框賦的值。
如果沒有指定其中一個屬性則用另一個屬性替代(即value和label值一樣),如下:
如果label和value都沒有指定,則無法用於autocomplete的提示。
另外需要注意,對於從服務器端輸出的JSON的key必須用雙引號,如下:
否則可能會出現parsererror錯誤。
主要的參數
jQuery UI Autocomplete常用的參數有:
- Source:用於指定數據來源,類型為String、Array、Function
- String:用於ajax請求的服務器端地址,返回Array/JSON格式
- Array:即字符串數組 或 JSON數組
- Function(request, response):通過request.term獲得輸入的值,response([Array])來呈現數據;(JSONP是這種方式)
- minLength:當輸入框內字符串長度達到minLength時,激活Autocomplete
- autoFocus:當Autocomplete選擇菜單彈出時,自動選中第一個
- delay:即延遲多少毫秒激活Autocomplete
其他不常用的就不羅列了。
使用方法
假如頁面上有以下輸入框:
<input type="text" id="autocomp" />
AJAX請求
通過指定source為服務器端的地址來實現,如下:
1
2
3
4
|
$(
"#autocomp"
).autocomplete({
source:
"remote.ashx"
,
minLength: 2
});
|
然后在服務器端接收,並輸出相應結果,注意默認傳遞的參數名稱為term:
public void ProcessRequest(HttpContext context) { // 查詢的參數名稱默認為term string query = context.Request.QueryString["term"]; context.Response.ContentType = "text/javascript"; //輸出字符串數組 或者 JSON 數組 context.Response.Write("[{\"label\":\"博客園\",\"value\":\"cnblogs\"},{\"label\":\"囧月\",\"value\":\"囧月\"}]"); }
本地Array/JSON數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// 本地字符串數組
var
availableTags = [
"C#"
,
"C++"
,
"Java"
,
"JavaScript"
,
"ASP"
,
"ASP.NET"
,
"JSP"
,
"PHP"
,
"Python"
,
"Ruby"
];
$(
"#local1"
).autocomplete({
source: availableTags
});
// 本地json數組
var
availableTagsJSON = [
{ label:
"C# Language"
, value:
"C#"
},
{ label:
"C++ Language"
, value:
"C++"
},
{ label:
"Java Language"
, value:
"Java"
},
{ label:
"JavaScript Language"
, value:
"JavaScript"
},
{ label:
"ASP.NET"
, value:
"ASP.NET"
},
{ label:
"JSP"
, value:
"JSP"
},
{ label:
"PHP"
, value:
"PHP"
},
{ label:
"Python"
, value:
"Python"
},
{ label:
"Ruby"
, value:
"Ruby"
}
];
$(
"#local2"
).autocomplete({
source: availableTagsJSON
});
|
Callback Function方式
通過指定source為自定義函數來實現自定義數據的獲取,函數主要有2個參數(request,response),分別用於獲取輸入的值、呈現結果
本地Array方式獲取數據(模仿新浪微博的登錄)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
var
hosts = [
"gmail.com"
,
"live.com"
,
"hotmail.com"
,
"yahoo.com"
,
"cnblogs.com"
,
"火星.com"
,
"囧月.com"
];
$(
"#email1"
).autocomplete({
autoFocus:
true
,
source:
function
(request, response) {
var
term = request.term,
//request.term為輸入的字符串
ix = term.indexOf(
"@"
),
name = term,
// 用戶名
host =
""
,
// 域名
result = [];
// 結果
result.push(term);
// result.push({ label: term, value: term }); // json格式
if
(ix > -1) {
name = term.slice(0, ix);
host = term.slice(ix + 1);
}
if
(name) {
var
findedHosts = (host ? $.grep(hosts,
function
(value) {
return
value.indexOf(host) > -1;
}) : hosts),
findedResults = $.map(findedHosts,
function
(value) {
return
name +
"@"
+ value;
//返回字符串格式
// return { label: name + " @ " + value, value: name + "@" + value }; // json格式
});
result = result.concat($.makeArray(findedResults));
}
response(result);
//呈現結果
}
});
|
JSONP方式獲取數據
直接從官方DEMO拿來的,通過發送ajax請求到遠程服務器,然后對返回結果進行處理,最后通過response來呈現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
$(
"#jsonp"
).autocomplete({
source:
function
(request, response) {
$.ajax({
dataType:
"jsonp"
,
data: {
featureClass:
"P"
,
style:
"full"
,
maxRows: 12,
name_startsWith: request.term
},
success:
function
(data) {
response($.map(data.geonames,
function
(item) {
return
{
label: item.name + (item.adminName1 ?
", "
+ item.adminName1 :
""
) +
", "
+ item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2
});
|
主要的事件
jQuery UI Autocomplete有一些事件,可用於在一些階段進行額外的控制:
- create(event, ui):Autocomplete創建時,可以在此事件中,對外觀進行一些控制
- search(event, ui): 在開始請求之前,可以在此事件中返回false來取消請求
- open(event, ui):Autocomplete的結果列表彈出時
- focus(event, ui):Autocomplete的結果列表任意一項獲得焦點時,ui.item為獲得焦點的項
- select(event, ui):Autocomplete的結果列表任意一項選中時,ui.item為選中的項
- close(event, ui):Autocomplete的結果列表關閉時
- change(event, ui):當值改變時,ui.item為選中的項
這些事件的ui參數的item屬性(如果有的話)默認有label和value屬性,不管在source中設置的數據是Array還是JSON數組,如下3種:
假如是第三種的話,還可以得到ui.item.id的值。
這些事件可以通過2種方式來綁定,如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
// 在參數中
$(
"#autocomp"
).autocomplete({
source: availableTags
, select:
function
(e, ui) {
alert(ui.item.value)
}
});
// 通過bind來綁定
$(
"#autocomp"
).bind(
"autocompleteselect"
,
function
(e, ui) {
alert(ui.item.value);
});
|
通過bind來綁定的方式使用的事件名稱為"autocomplete"+事件名稱,如"select"就是"autocompleteselect"。
多個值的Autocomplete
一般情況下,輸入框的autocomplete僅需要一個值就可以(如:javascript);假如需要多個值(如:javascript,c#,asp.net),則需要綁定一些事件來進行額外處理:
- 在focus事件中返回false,避免輸入框的值被autocomplete的單個值取代
- 在select事件中組合多個值
- 在元素的keydown事件做一些處理,理由同1
- 使用callback function方式的source,來獲取最后輸入的值,並呈現結果
還是直接拿官方DEMO的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
// 按逗號分隔多個值
function
split(val) {
return
val.split(/,\s*/);
}
// 提取輸入的最后一個值
function
extractLast(term) {
return
split(term).pop();
}
// 按Tab鍵時,取消為輸入框設置value
function
keyDown(event) {
if
(event.keyCode === $.ui.keyCode.TAB &&
$(
this
).data(
"autocomplete"
).menu.active) {
event.preventDefault();
}
}
var
options = {
// 獲得焦點
focus:
function
() {
// prevent value inserted on focus
return
false
;
},
// 從autocomplete彈出菜單選擇一個值時,加到輸入框最后,並以逗號分隔
select:
function
(event, ui) {
var
terms = split(
this
.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push(
""
);
this
.value = terms.join(
", "
);
return
false
;
}
};
// 多個值,本地數組
$(
"#local3"
).bind(
"keydown"
, keyDown)
.autocomplete($.extend(options, {
minLength: 2,
source:
function
(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
}
}));
// 多個值,ajax返回json
$(
"#ajax3"
).bind(
"keydown"
, keyDown)
.autocomplete($.extend(options, {
minLength: 2,
source:
function
(request, response) {
$.getJSON(
"remoteJSON.ashx"
, {
term: extractLast(request.term)
}, response);
}
}));
|
結尾
最后,放上代碼:點擊下載。
更多的資料請看jQuery UI Autocomplete官方演示:http://jqueryui.com/demos/autocomplete