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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2382497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:23:12  来源:igfitidea点击:

jQuery UI Autocomplete widget search configuration

jqueryjquery-uijquery-pluginsautocompletejquery-ui-autocomplete

提问by dev.e.loper

I'm looking into using the jQuery UI autocompletewidget to implement user lookup by first or last name. It looks like by default autocomplete looks up words by character sequence no matter its occurrence in a word. So if you have data such as: javascript, asp, haskelland you type in 'as'you will get all three. I would like it to only match beginning of the word. So in above example you get only 'asp'. Is there a way to configure the autocomplete widget to do this?

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

Ultimately it would be even better to match by beginning of first or last namelike it is in Gmail.

最终,通过名字或姓氏开头匹配会更好,就像在 Gmail 中一样。

Note: I'm trying to figure out a way to do this using the jQuery UI widget specifically. Since I'm already using jQuery UI in my project, I'm planning to stick with it and try not adding additional libraries to my web application.

注意:我正试图找出一种方法来专门使用 jQuery UI 小部件来做到这一点。由于我已经在我的项目中使用了 jQuery UI,我打算坚持使用它并尝试不向我的 Web 应用程序添加额外的库。

回答by Cheeso

In jQuery UI v1.8rc3, the autocomplete widgetaccepts a sourceoption which can be either a string, an array, or a callback function. If it's a string, autocomplete does a GET on that URL to get options/suggestions. If an array, autocomplete does a search, as you pointed out, for the presence of the typed chars in any position in the terms of the array. The final variant is what you want - the callback function.

在 jQuery UI v1.8rc3 中,自动完成小部件接受一个选项,它可以是字符串、数组或回调函数。如果它是一个字符串,自动完成会对该 URL 执行 GET 以获取选项/建议。如果是数组,则自动完成功能会按照您所指出的那样搜索数组中任何位置是否存在键入的字符。最后一个变体就是你想要的——回调函数。

From the autocomplete documentation:

从自动完成文档:

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

? A requestobject, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field that is set to do autocomplete, the request.termwill hold "new yo".
? A responsefunction, a callback which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and must be an array in the format allowed for simple local data: String-Array or Object-Array with label/value/both properties.

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

? 一个request对象,具有称为“term”的单个属性,它指的是当前文本输入中的值。例如,当用户在设置为自动完成的城市字段中输入“new yo”时,request.term将保留“new yo”。
? 一个response函数,一个回调,它需要一个参数来包含向用户建议的数据。此数据应根据提供的术语进行过滤,并且必须是简单本地数据所允许格式的数组:具有标签/值/两个属性的字符串数组或对象数组。

Example code:

示例代码:

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 );
    }
});

A few key points:

几个关键点:

  • the call to $.ui.autocomplete.escapeRegex(req.term);That escapesthe search term so that any regex-meaningful terms in the text typed by the user are treated as plain text. For example, the dot (.) is meaningful to regex. I learned of this escapeRegex function by reading the autocomplete source code.
  • the line with new Regexp(). It specifies a regexp beginning with ^ (Circumflex), which implies, it will match only when the typed characters appear at the beginning of the term in the array, which is what you wanted. It also uses the "i" option which implies a case-insensitive match.
  • the $.grep()utility just calls the provided function on each term in the provided array. The function in this case simply uses the regexp to see if the term in the array is a match for what was typed.
  • finally, the responseFn() is invoked with the result of the search.
  • $.ui.autocomplete.escapeRegex(req.term);That的调用会转义搜索词,以便用户键入的文本中的任何正则表达式有意义的词都被视为纯文本。例如,点 (.) 对正则表达式有意义。我通过阅读自动完成源代码了解了这个 escapeRegex 函数。
  • new Regexp(). 它指定了一个以 ^ (Circumflex) 开头的正则表达式,这意味着只有当键入的字符出现在数组中的术语开头时,它才会匹配,这正是您想要的。它还使用“i”选项,这意味着不区分大小写的匹配。
  • $.grep()实用程序只是在提供的数组中的每个术语上调用提供的函数。在这种情况下,该函数仅使用正则表达式来查看数组中的术语是否与键入的内容匹配。
  • 最后,使用搜索结果调用 responseFn()。

working demo: http://jsbin.com/ezifi

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

what it looks like:

它看起来像什么:

alt text

替代文字

Just a note: I find the documentation on autocomplete to be pretty immature at this point. I didn't find examples that did this, and I couldn't find working doc on which .css files were necessary or which .css classes would be used. I learned all this from inspecting the code.

请注意:我发现有关自动完成的文档在这一点上还很不成熟。我没有找到执行此操作的示例,也找不到有关哪些 .css 文件是必需的或将使用哪些 .css 类的工作文档。我从检查代码中学到了这一切。

See also, how can I custom-format the Autocomplete plug-in results?

另请参阅,如何自定义格式自动完成插件结果?

回答by Cheeso

I use the autocomplete from devbridge. http://www.devbridge.com/projects/autocomplete/jquery/

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

It matches on the beginning characters, only.

它只匹配开头的字符。

alt text

替代文字

As far as matching based on first name or last name, you'd just have to supply a lookup list with the first and last name.

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

Example usage:

用法示例:

  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
      };

The lookupoption that you pass to initialize the autocomplete control can be a list, or an object. The above showed a simple list. If you want some data attached to the suggestions that get returned, then make the lookupoption an object, like this:

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

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

回答by Phil Rykoff

thx cheeso for intrducing jsbin.com,

感谢 cheeso 介绍 jsbin.com,

i extended your code to support first- and lastname matches, too.

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

  $("#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 );
      }
  });

demo: http://jsbin.com/ufimu3/

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

type 'an' or 're'

输入“an”或“re”

回答by Nader

If you want to search the beginning of each word in the string, a more elegant solution to henchman's is to take cheeso's but just use the regexp word boundary special character:

如果你想搜索字符串中每个单词的开头,一个更优雅的解决方法是使用 cheeso's 但只使用正则表达式单词边界特殊字符:

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

Example: http://jsbin.com/utojoh/2(try searching for 'bl')

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

回答by Paul D. Waite

There's another jQuery autocomplete plug-inthat optionally searches just at the start of each item (the option is matchContains=false, I think that's the default too).

还有另一个 jQuery 自动完成插件,可以选择在每个项目的开头进行搜索(选项是matchContains=false,我认为这也是默认设置)。

Given the absence of such an option in the jQuery UI plugin, I'm guessing you'll either have to use a different plugin, or rewrite the one you're using now.

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

回答by Mark

Where are you getting the data to populate the autocomplete? Is it from a database? If so, you can do what you want in your query and only return results that match the beginning of each word (first/last name)

你从哪里得到数据来填充自动完成?它来自数据库吗?如果是这样,您可以在查询中执行您想要的操作,并且只返回与每个单词开头(名字/姓氏)匹配的结果