jQuery UI Autocomplete使用startsWith

Bar*_*art 32 jquery jquery-ui autocomplete

我正在使用jQuery UI Autocomplete和本地数据源(source: myArray).我希望自动完成只建议输入的字符串开头的结果,而不是默认的不区分大小写的包含搜索.是否有一个简单的解决方案或我必须提供我的自定义搜索/源回调?

Bum*_*tle 28

看到这个:

匹配开始词:

http://blog.miroslavpopovic.com/jqueryui-autocomplete-filter-words-starting-with-term

他会覆盖自动完成过滤器方法.我使用它,效果很好.

// Overrides the default autocomplete filter function to search only from the beginning of the string
$.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);
    });
};
Run Code Online (Sandbox Code Playgroud)

匹配词:

匹配开始与字符串中的任何单词匹配.

例如"LHR london"与"london"相匹配

var matcher = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(term), "i");
Run Code Online (Sandbox Code Playgroud)

\ b在字边界处断言位置(^\w |\w $ |\W\w |\w\W)


Bar*_*art 14

目前我已经这样做了,不确定是否有更好的解决方案:

source: function(request, response) {
    var filteredArray = $.map(orignalArray, function(item) {
        if( item.value.startsWith(request.term)){
            return item;
        }
        else{
            return null;
        }
    });
    response(filteredArray);
},
Run Code Online (Sandbox Code Playgroud)

这种方法还可以对要显示的项目数量施加限制(例如10项).