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

发布于 2024-08-24 15:47:25 字数 567 浏览 4 评论 0原文

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

最终,最好按名字或姓氏的开头进行匹配,例如它在 Gmail 中。

注意:我正在尝试找出一种专门使用 jQuery UI 小部件来执行此操作的方法。由于我已经在我的项目中使用了 jQuery UI,因此我打算坚持使用它并尝试不向我的 Web 应用程序添加其他库。

I'm looking into using the jQuery UI autocomplete widget 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, haskell and 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?

Ultimately it would be even better to match by beginning of first or last name like it is in 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

能怎样 2024-08-31 15:47:25

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

来自自动完成文档:

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

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

示例代码:

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 类的工作文档。我通过检查代码了解到了这一切。

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

In jQuery UI v1.8rc3, the autocomplete widget accepts a source option 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.

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 request object, 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.term will hold "new yo".
• A response function, 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.

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 escapes the 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.

working demo: 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.

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

甜味拾荒者 2024-08-31 15:47:25

感谢 cheeso 介绍 jsbin.com,

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

  $("#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'

thx cheeso for intrducing 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/

type 'an' or 're'

最笨的告白 2024-08-31 15:47:25

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

仅匹配开头字符。

替代文本

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

用法示例:

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

I use the autocomplete from 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 lookup option 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 lookup option an object, like this:

var lookuplist = {
    suggestions:   [ "Jan", "Feb", "Mar", "Apr", "May" ],
    data :         [ 31, 28, 31, 30, 31, ]
};
请叫√我孤独 2024-08-31 15:47:25

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

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

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

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:

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

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

玩物 2024-08-31 15:47:25

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

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

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

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.

给我一枪 2024-08-31 15:47:25

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

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文