如果您使用对象,jQueryUI 需要一个值和/或标签字段:
支持多种类型:
数组:数组可用于本地数据。支持的格式有两种: 字符串数组:[ "Choice1", "Choice2" ]
具有标签和值属性的对象数组: [ { label: "Choice1", value: "value1" }, ... ] 标签属性显示在建议菜单中。当用户选择一个项目时,该值将被插入到输入元素中。如果只指定了一个属性,它将用于两者,例如,如果您只提供值属性,则该值也将用作标签。
来源:http ://api.jqueryui.com/autocomplete/#option-source
考虑到这一点,您必须采用您的数据,包括 value 属性,您只需将其分配给名称(例如$.each(employees, function(){ this.value = this.name });
...)
Now the other thing you have to define, is how you want to filter. This can be done by defining the source.
Example:
$("#txtEmployeeName").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var matching = $.grep(employees, function (value) {
var name = value.value;
var id = value.id;
return matcher.test(name) || matcher.test(id);
});
response(matching);
}
});
Fiddler example: http://fiddle.jshell.net/YJkTr/
Full code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function () {
var employees = [
{ "value": "Tom", "id": "1" },
{ "value": "Stefan", "id": "2" },
{ "value": "Martin", "id": "3" },
{ "value": "Sara", "id": "4" },
{ "value": "Valarie", "id": "5" },
]
$("#txtEmployeeName").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var matching = $.grep(employees, function (value) {
var name = value.value;
var id = value.id;
return matcher.test(name) || matcher.test(id);
});
response(matching);
}
});
});
</script>
</head>
<body style="font-size: 62.5%;">
<div class="ui-widget">
<form>
<label for="txtEmployeeName">Developer:</label>
<input id="txtEmployeeName" />
</form>
</div>
</body>
</html>