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
    示例:

    简化了示例——我重复了两次,并不是有意的。