首页 文章

jQuery UI自动完成小部件搜索配置

提问于
浏览
64

我正在研究使用jQuery UI autocomplete小部件来实现用姓或名的用户查找 . 看起来默认情况下,自动完成按字符序列查找单词,无论它出现在单词中 . 因此,如果您有以下数据: javascript, asp, haskell 并输入 'as' ,您将获得全部三个 . 我希望它只匹配单词的开头 . 所以在上面的例子中你只得到 'asp' . 有没有办法配置自动完成小部件来执行此操作?

最终,像Gmail一样,它会更好 .

注意:我正在尝试使用jQuery UI小部件专门找到一种方法 . 由于我已经在我的项目中使用jQuery UI,我计划坚持使用它并尝试不向我的Web应用程序添加额外的库 .

6 回答

  • 126

    在jQuery UI v1.8rc3中,the autocomplete widget接受source选项,该选项可以是字符串,数组或回调函数 . 如果它是一个字符串,自动完成功能会对该URL进行GET以获取选项/建议 . 如果数组,自动完成执行搜索,正如您所指出的那样,在数组术语中的任何位置都存在类型化的字符 . 最终的变体是你想要的 - 回调函数 .

    从自动完成文档:

    第三种变体,即回调,提供了最大的灵活性,可用于将任何数据源连接到自动完成 . 回调有两个参数:•一个请求对象,具有一个名为“term”的属性,它引用当前文本输入中的值 . 例如,当用户在设置为执行自动完成的城市字段中输入“new yo”时,request.term将保持“new yo” . •响应函数,一种回调,它要求单个参数包含要向用户建议的数据 . 此数据应根据提供的术语进行过滤,并且必须是允许简单本地数据格式的数组:String-Array或具有label / value / both属性的Object-Array .

    示例代码:

    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); 的调用会转义搜索词,以便用户输入的文本中的任何正则有意义的术语都被视为纯文本 . 例如,点( . )对正则表达式有意义 . 我通过阅读自动完成源代码了解了这个escapeRegex函数 .

    • new Regexp() 的行 . 它指定以^(Circumflex)开头的正则表达式,这意味着,只有当类型字符出现在数组中术语的开头时才会匹配,这就是您想要的 . 它还使用"i"选项,这意味着不区分大小写的匹配 .

    • $.grep() 实用程序只调用提供的数组中每个术语的提供函数 . 在这种情况下,函数只使用正则表达式来查看数组中的术语是否与键入的内容相匹配 .

    • 最后,使用搜索结果调用responseFn() .

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

    它看起来像什么:

    alt text

    请注意:我发现自动完成的文档在这一点上还不成熟 . 我找不到这样做的例子,我找不到工作文件,其中.css文件是必需的,或者使用哪些.css类 . 我从检查代码中学到了这一切 .

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

  • 2

    我使用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 选项可以是列表或对象 . 以上显示了一个简单的列表 . 如果您希望将某些数据附加到返回的建议,那么将 lookup 选项设为对象,如下所示:

    var lookuplist = {
        suggestions:   [ "Jan", "Feb", "Mar", "Apr", "May" ],
        data :         [ 31, 28, 31, 30, 31, ]
    };
    
  • 0

    thx cheeso引导jsbin.com,

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

    $("#input1").autocomplete({
          source: function(req, responseFn) {
              addMessage("search on: '" + req.term + "'
    "); 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
    "); responseFn( matches ); } });

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

    输入'an'或're'

  • 0

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

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

    示例:http://jsbin.com/utojoh/2(尝试搜索'bl')

  • 5

    another jQuery autocomplete plug-in可选择在每个项目的开头搜索(选项是matchContains=false,我认为这也是默认值) .

    鉴于jQuery UI插件中没有这样的选项,我猜你要么必须使用不同的插件,或重写你现在使用的那个 .

  • 6

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

相关问题