代码之家  ›  专栏  ›  技术社区  ›  dev.e.loper

jquery ui自动完成小部件搜索配置

  •  64
  • dev.e.loper  · 技术社区  · 15 年前

    我正在考虑使用 jQuery UI autocomplete 按名字或姓氏实现用户查找的小部件。默认情况下,autocomplete按字符顺序查找单词,而不管它在单词中的出现情况如何。因此,如果你有如下数据: javascript, asp, haskell 然后你输入 'as' 你将得到所有三个。我希望它只与单词开头匹配。所以在上面的例子中 'asp' . 是否有方法配置自动完成小部件来完成此操作?

    最终,最好是 match by beginning of first or last name 就像在Gmail里一样。

    注意:我正在尝试使用jquery ui小部件来实现这一点。因为我已经在我的项目中使用jquery ui,所以我计划坚持使用它,并尝试不向我的web应用程序添加额外的库。

    6 回复  |  直到 7 年前
        1
  •  127
  •   Martijn Pieters    7 年前

    在jquery ui v1.8rc3中, the autocomplete widget 接受一 source 选项,可以是字符串、数组或回调函数。如果是字符串,autocomplete会对该url执行get以获取选项/建议。如果是数组,autocomplete会像您指出的那样,搜索数组中任何位置是否存在键入的字符。最后一个变量就是你想要的-回调函数。

    从自动完成文档:

    第三个变体回调提供了最大的灵活性,可用于将任何数据源连接到自动完成。回调得到两个参数:

    request 对象,具有一个名为“term”的属性,该属性引用当前文本输入中的值。例如,当用户在设置为自动完成的城市字段中输入“new yo”时, request.term 将举行“新哟”。
    response 函数,一个回调函数,它期望单个参数包含向用户建议的数据。此数据应根据提供的术语进行筛选,并且必须是简单本地数据所允许的格式的数组:字符串数组或具有label/value/两个属性的对象数组。

    示例代码:

    var wordlist= [ "about", "above", "across", "after", "against",
                    "along", "among", "around", "at", "before", 
                    "behind", "below", "beneath", "beside", "between", 
                    "beyond", "but", "by", "despite", "down", "during", 
                    "except", "for", "from", "in", "inside", "into", 
                    "like", "near", "of", "off", "on", "onto", "out", 
                    "outside", "over", "past", "since", "through", 
                    "throughout", "till", "to", "toward", "under", 
                    "underneath", "until", "up", "upon", "with", 
                    "within", "without"] ; 
    
    $("#input1").autocomplete({
        // The source option can be an array of terms.  In this case, if
        // the typed characters appear in any position in a term, then the
        // term is included in the autocomplete list.
        // The source option can also be a function that performs the search,
        // and calls a response function with the matched entries.
        source: function(req, responseFn) {
            var re = $.ui.autocomplete.escapeRegex(req.term);
            var matcher = new RegExp( "^" + re, "i" );
            var a = $.grep( wordlist, function(item,index){
                return matcher.test(item);
            });
            responseFn( a );
        }
    });
    

    几个要点:

    • 呼唤 $.ui.autocomplete.escapeRegex(req.term); 逃逸 搜索词 这样,用户键入的文本中任何有意义的regex术语都被视为纯文本。例如,点(.)对regex有意义。通过阅读自动完成的源代码,我了解了这个escaperegex函数。
    • 排队 new Regexp() . 它指定了一个以^(扬抑符)开头的regexp,这意味着,只有当类型化字符出现在数组中术语的开头时,它才会匹配,这正是您想要的。它还使用“i”选项,这意味着不区分大小写的匹配。
    • 这个 $.grep() 实用程序只对所提供数组中的每个项调用所提供的函数。本例中的函数只是使用regexp来查看数组中的项是否与类型匹配。
    • 最后,使用搜索结果调用responseFn()。

    工作演示: http://jsbin.com/ezifi

    它是什么样子的:

    alt text

    只需注意:我发现关于autocomplete的文档目前还很不成熟。我没有找到这样做的例子,也找不到工作文档,其中.css文件是必需的,或者.css类将被使用。我从检查代码中学到了这些。

    也见 how can I custom-format the Autocomplete plug-in results?

        2
  •  6
  •   Cheeso    15 年前

    我使用devbridge的自动完成功能。 http://www.devbridge.com/projects/autocomplete/jquery/

    它只匹配开头的字符。

    alt text http://i46.tinypic.com/2ihq7pd.jpg

    至于基于名字或姓氏的匹配,您只需提供一个包含名字和姓氏的查找列表。

    示例用法:

      var wordlist = [
          'January', 'February', 'March', 'April', 'May', 'June',
          'July', 'August', 'September', 'October', 'November',
          'December' ]; 
    
          var acOptions = {
              minChars:2,
              delimiter: /(,|;)\s*/, // regex or character
              maxHeight:400,
              width:300,
              zIndex: 9999,
              deferRequestBy: 10, // miliseconds
    
              // callback function:
              onSelect: function(value, data){
                  //$('#input1').autocomplete(acOptions);
                  if (typeof data == "undefined") {
                      alert('You selected: ' + value );
                  }else {
                      alert('You selected: ' + value + ', ' + data);
                  }
              },
    
              // local autosuggest options:
              lookup: wordlist
          };
    

    这个 lookup 用于初始化自动完成控件的选项可以是列表或对象。上面显示了一个简单的列表。如果您希望将一些数据附加到返回的建议,请将 查找 选择一个对象,如下所示:

    var lookuplist = {
        suggestions:   [ "Jan", "Feb", "Mar", "Apr", "May" ],
        data :         [ 31, 28, 31, 30, 31, ]
    };
    
        3
  •  5
  •   Phil Rykoff    15 年前

    为intrducing jsbin.com提供的THX Cheeso,

    我扩展了你的代码以支持名字和姓氏匹配。

      $("#input1").autocomplete({
          source: function(req, responseFn) {
              addMessage("search on: '" + req.term + "'<br/>");
    
              var matches = new Array();
              var needle = req.term.toLowerCase();
    
              var len = wordlist.length;
              for(i = 0; i < len; ++i)
              {
                  var haystack = wordlist[i].toLowerCase();
                  if(haystack.indexOf(needle) == 0 ||
                     haystack.indexOf(" " + needle) != -1)
                  {
                      matches.push(wordlist[i]);
                  }
              }
    
              addMessage("Result: " + matches.length + " items<br/>");
              responseFn( matches );
          }
      });
    

    演示: http://jsbin.com/ufimu3/

    键入“an”或“re”

        4
  •  2
  •   Nader    13 年前

    如果要搜索字符串中每个单词的开头,henchman的一个更优雅的解决方案是使用cheeso的,但只使用regexp单词边界特殊字符:

    var matcher = new RegExp( "\\b" + re, "i" );
    

    例子: http://jsbin.com/utojoh/2 (尝试搜索“bl”)

        5
  •  0
  •   Paul D. Waite    15 年前

    那里有 another jQuery autocomplete plug-in 可以选择只在每个项目的开始处搜索(选项是 matchContains=false ,我认为这也是默认的)。

    鉴于jquery ui插件中没有这样一个选项,我猜您要么使用另一个插件,要么重写您现在使用的插件。

        6
  •  0
  •   Mark    15 年前

    从哪里获取数据来填充自动完成功能?是数据库里的吗?如果是,您可以在查询中执行所需的操作,并且只返回与每个单词开头(名字/姓氏)匹配的结果