jquery自动完成插件搜索
有一个插件 它只允许您搜索准确的字符串 所以我们假设这是数据jquery自动完成插件搜索,jquery,jquery-plugins,autocomplete,Jquery,Jquery Plugins,Autocomplete,有一个插件 它只允许您搜索准确的字符串 所以我们假设这是数据 [ ['apple is good'], ['apple grows on tree'], ['the tree and the apple'], ['red apple'], ['apple tree'] ] 现在搜索“苹果”应该显示所有 但当输入“苹果树”时,它只返回“苹果树” 我希望它返回smart结果(2、3和5) “苹果长在树上
[
['apple is good'],
['apple grows on tree'],
['the tree and the apple'],
['red apple'],
['apple tree']
]
现在搜索“苹果”应该显示所有
但当输入“苹果树”时,它只返回“苹果树”我希望它返回smart结果(2、3和5)
- “苹果长在树上”
- “树和苹果”
- “苹果树”
$("#textInputEle").autocomplete({
url:"path/to/data.json",
filter: function(result, filter) {
//whats should this function be?
}
});
我相信jqueryautocomplete的开箱即用功能只会返回包含短语“appletree”的结果。因此,它将从您的示例中返回#5,但对于诸如“他住在一棵苹果树附近”和“苹果树是她院子里最大的”之类的短语,它也将返回真值。您可以使用
过滤器
选项来提供您自己的过滤逻辑
您提供的函数采用result
和filter
参数。filter
参数是用户搜索的内容。结果
参数是建议列表中的一项。函数必须返回true
(如果建议匹配),或false
(如果建议不匹配)
执行您试图完成的任务的逻辑可能如下所示:
$("#auto").autocomplete({
data: [
['apple is good'],
['apple grows on tree'],
['the tree and the apple'],
['red apple'],
['apple tree']
],
filter: function(result, filter) {
var terms = filter.split(" "),
match = true,
i = 0,
regex;
for (; match && i < terms.length; i++) {
regex = new RegExp(terms[i]);
match = match && regex.test(result.value);
}
return match;
}
});
“
)传递的结果拆分为一个术语数组
$("#auto").autocomplete({
data: [
['apple is good'],
['apple grows on tree'],
['the tree and the apple'],
['red apple'],
['apple tree']
],
filter: function(result, filter) {
var terms = filter.split(" "),
match = true,
i = 0,
regex;
for (; match && i < terms.length; i++) {
regex = new RegExp(terms[i]);
match = match && regex.test(result.value);
}
return match;
}
});
$(“#自动”).autocomplete({
数据:[
[“苹果是好的”],
[“苹果长在树上”],
[“树和苹果”],
[“红苹果”],
[“苹果树”]
],
过滤器:功能(结果、过滤器){
var terms=filter.split(“”),
匹配=真,
i=0,
正则表达式;
对于(;match&&i
示例:简化了示例——我重复了两次,并不是有意的。