更新:一天后,我发现一个插件对我的项目环境好 10000 倍。 Select2,查看“加载远程数据”示例。
原答案:
我升级了之前的示例以使用当前的 jQuery 版本:
JS Fiddle example with jQuery 2.1.4 and jQuery UI 1.11.4
此外,我将此自动完成功能更改为用作自定义小部件,并包括对键盘导航的支持。
代码:
$.widget('custom.tableAutocomplete', $.ui.autocomplete, {
options: {
open: function (event, ui) {
// Hack to prevent a 'menufocus' error when doing sequential searches using only the keyboard
$('.ui-autocomplete .ui-menu-item:first').trigger('mouseover');
},
focus: function (event, ui) {
event.preventDefault();
}
},
_create: function () {
this._super();
// Using a table makes the autocomplete forget how to menu.
// With this we can skip the header row and navigate again via keyboard.
this.widget().menu("option", "items", ".ui-menu-item");
},
_renderMenu: function (ul, items) {
var self = this;
var $table = $('<table class="table-autocomplete">'),
$thead = $('<thead>'),
$headerRow = $('<tr>'),
$tbody = $('<tbody>');
$.each(self.options.columns, function (index, columnMapping) {
$('<th>').text(columnMapping.title).appendTo($headerRow);
});
$thead.append($headerRow);
$table.append($thead);
$table.append($tbody);
ul.html($table);
$.each(items, function (index, item) {
self._renderItemData(ul, ul.find("table tbody"), item);
});
},
_renderItemData: function (ul, table, item) {
return this._renderItem(table, item).data("ui-autocomplete-item", item);
},
_renderItem: function (table, item) {
var self = this;
var $tr = $('<tr class="ui-menu-item" role="presentation">');
$.each(self.options.columns, function (index, columnMapping) {
var cellContent = !item[columnMapping.field] ? '' : item[columnMapping.field];
$('<td>').text(cellContent).appendTo($tr);
});
return $tr.appendTo(table);
}
});
$(function () {
var result_sample = [{
"id": 26,
"value": "Ladislau Santos Jr.",
"email": "klber_moraes@email.net",
"address": "9867 Robert St"
}, {
"id": 14,
"value": "Pablo Santos",
"email": "pablo@xpto.org",
"address": "7540 Moreira Ponte"
}, {
"id": 13,
"value": "Souza, Nogueira e Santos",
"email": null,
"address": "3504 Melo Marginal"
}];
$('input#search_field').tableAutocomplete({
source: result_sample,
columns: [{
field: 'value',
title: 'Name'
}, {
field: 'email',
title: 'E-mail'
}, {
field: 'address',
title: 'Address'
}],
delay: 500,
select: function (event, ui) {
if (ui.item != undefined) {
$(this).val(ui.item.value);
$('#selected_id').val(ui.item.id);
}
return false;
}
});
});