【问题标题】:Jquery search from the start of the letterjquery从字母开始搜索
【发布时间】:2018-03-05 21:32:40
【问题描述】:

我正在使用 jQuery UI 自动完成功能,它不会搜索以字母开头的项目。请有人帮助我!

这是我的代码:

var my= [
    "Urbana, IL",
    "Ursa, IL",
    "Utica, IL",
    "Valier, IL",
    "Valmeyer, IL",
    "Van-Orin, IL",
    "Vandalia, IL"
];

my.sort();

$("#location-input").autocomplete({ 
    maxResults: 15,
    delay:1,
    minLength:1,
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(my, request.term);

        response(results.slice(0, this.options.maxResults));
    }
});

【问题讨论】:

    标签: jquery jquery-ui autocomplete jquery-ui-autocomplete


    【解决方案1】:

    如果输入的字母存在于单词中的任何位置,您的代码匹配。如果您想只匹配开始键入的字母的项目,jQuery 建议使用动态正则表达式,如下所示:

    <html>
    <head>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
        $(function() {
          var my = [
            "Urbana, IL",
            "Ursa, IL",
            "Utica, IL",
            "Valier, IL",
            "Valmeyer, IL",
            "Van-Orin, IL",
            "Vandalia, IL"
          ];
          my.sort();
    
          $("#location-input").autocomplete({
            maxResults: 15,
            delay: 1,
            minLength: 1,
            source: function(request, response) {
              var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
              response($.grep(my, function(item) {
                  return matcher.test( item );
              }).slice(0, this.options.maxResults));
            }
          });
        });
      </script>
    </head>
    <body>
      Type "v" (will find). Type "i" (won't find): <input type="text" id="location-input">
    </body>
    </html>

    在上面,添加了.slice(0, this.options.maxResults) 以将结果限制为maxResults。在示例 15 中。

    【讨论】:

    • 感谢它的工作!但我有一个问题。我的数组中的项目比我向您展示的要多,当我搜索它的速度非常慢时,它没有显示为什么我的 maxResults 为 15 的结果。我如何告诉它只向我发送最大化结果
    • 什么是“向我发送格言”?
    • 我的意思是这个 maxResults: 15,
    • 添加了.slice(0, this.options.maxResults)。检查更新的答案。
    • 没问题,非常感谢
    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多