use*_*632 5 javascript jquery jquery-ui autocomplete jquery-ui-autocomplete
我不想进行文字匹配,而是通过正则表达式选择结果.
我可以覆盖自动完成的默认行为来完成此操作,还是需要替代结构?
有一种内置方法可以做到这一点:只为source
自动完成小部件中的选项提供一个函数:
var items = ['Foo', 'Bar', 'Hello', 'Goodbye', '1234'];
$("#autocomplete").autocomplete({
source: function(request, response) {
// The term the user searched for;
var term = request.term;
// Extract matching items:
var matches = $.grep(items, function(item, index) {
// Build your regex here:
return /\d+/.test(item);
});
// let autocomplete know the results:
response(matches);
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,由于我使用的简单正则表达式,此示例将始终返回"1234".更有用的可能是根据术语(也可能)构建正则表达式.
这实际上与小部件本身过滤结果的方式非常相似.查看此行以了解过滤器功能和此行,以了解如果提供数组作为source
选项,它将如何调用.