Jquery 从字母开头搜索

Jquery search from the start of the letter

我正在使用 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 建议使用动态正则表达式,如下所示:

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