不幸的是,似乎 jQueryUI 自动完成功能不允许在数组源上执行此操作。但是,您可以挂钩插件的_initSource函数以在搜索中强制使用“开头”正则表达式标记 ( ^ ),如下所示。
我认为这可能被忽略了,因为它的大部分使用被认为是在远程检索中。无论哪种方式,都不是一个很好的解决方案,但由于正则表达式剥离功能,这是唯一想到的解决方案。
$.ui.autocomplete.prototype._initSource = function() {
var array,
url;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
// escape regex characters
var matcher = new RegExp( "^"+$.ui.autocomplete.escapeRegex(request.term), "i" );
response( $.grep( array, function(value) {
return matcher.test( value.label || value.value || value );
}) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
$.getJSON( url, request, response );
};
} else {
this.source = this.options.source;
}
};
$("#countries").autocomplete({
source: ["India","Indonesia","Argentina"],
minLength: 2
});