我为机场提供了jQuery自动填充功能。我的数据集包含标签和值。 样品:
var Airports = [
{ "label": "DMB - Dzhambyl, Dzhambyl Airport", "value": "DMB" },
{ "label": "EMA - Nottingham, Nottingham East Midlands Airport", "value": "EMA" },
{ "label": "HAM - Hamburg, Hamburg Airport", "value": "HAM" }
];
当我进入HAM(这是汉堡机场的3LC)时,我目前得到所有这三个项目。但我只想看看汉堡,汉堡机场和#34;如果此项的值与确切的搜索请求匹配。还应该可以找到所有条目,例如: "堡"如果我想搜索那个。
答案 0 :(得分:0)
从您的问题描述中听起来您只想从值字符串的开头进行匹配。在这种情况下,您可以为自动完成创建自己的过滤方法,如下所示:
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
答案 1 :(得分:0)
不知道是谁投了这个问题,为什么......但是这里有解决方案,以便将来需要类似的东西:
$(function () {
var Airports = [
{ "label": "DMB - Dzhambyl, Dzhambyl Airport", "value": "DMB" },
{ "label": "EMA - Nottingham, Nottingham East Midlands Airport", "value": "EMA" },
{ "label": "HAM - Hamburg, Hamburg Airport", "value": "HAM" }
];
$("#depart").autocomplete({
source: function (request, response) {
var term = $.ui.autocomplete.escapeRegex(request.term)
, startsWithMatcher = new RegExp("^" + term, "i")
, startsWith = $.grep(Airports, function(value) {
return startsWithMatcher.test(value.label || value.value || value);
})
, containsMatcher = new RegExp(term, "i")
, contains = $.grep(Airports, function (value) {
return $.inArray(value, startsWith) < 0 &&
containsMatcher.test(value.label || value.value || value);
});
response(startsWith.concat(contains));
},
minLength: 3
});
});