简体   繁体   English

修改jQuery自动完成功能以匹配建议输出

[英]Modifying jQuery Autocomplete functionality to match suggestions output

I have the following piece of code. 我有以下代码。

var data=["NYC - New York City", "LA - Los Angeles", "SF - San Francisco"];
$function(){
    $("#title").autocomplete({
        source: function(request, response){
            var matcher=new RegExp("^"+$ui.autocomplete.escapeRegex(request.term),"i");
            response($grep(data, function(item){
                return matcher.test(item);
            }));
        }
    });
});         

When I type NYC, I get 'NYC - New York City' in my list of suggestions. 当我输入NYC时,在建议列表中会显示“ NYC-New York City”。 Same for LA and SF. LA和SF相同。 However, when I type New York City, I do not get any suggestions. 但是,当我键入纽约市时,我没有得到任何建议。 Can anyone please help me with this issue? 谁能帮我解决这个问题? Thanks. 谢谢。

The regular expression used to match strings is searching from the beginning of the string ( "^" ) – you can remove this to match the typed string anywhere in the data strings: 用于匹配字符串的正则表达式是从字符串的开头( "^" )搜索–您可以删除它以匹配数据字符串中任何位置的键入字符串:

var matcher = new RegExp($ui.autocomplete.escapeRegex(request.term), "i");

Also, you can use word boundaries if you want to match from the beginning of a particular word: 另外,如果要从特定单词的开头进行匹配,则可以使用单词边界:

var matcher = new RegExp("\b" + $ui.autocomplete.escapeRegex(request.term), "i");

which for example if "an" were typed, it would match "Angeles" but not "San" or "Francisco". 例如,如果键入“ an”,它将匹配“ Angeles”,但不匹配“ San”或“ Francisco”。

Edit: 编辑:

Here is a JSFiddle ( https://jsfiddle.net/Lrtuyeph/ ) which shows the really simple example of just passing the data array as the source property – the default behavior does what you want it to do. 这是一个JSFiddle( https://jsfiddle.net/Lrtuyeph/ ),它显示了一个非常简单的示例,只是将data数组作为source属性进行传递-默认行为完成了您想要的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM