首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字母开头开始的Jquery搜索

从字母开头开始的Jquery搜索
EN

Stack Overflow用户
提问于 2018-03-05 21:32:40
回答 1查看 27关注 0票数 1

我正在使用jQuery UI自动完成,它不是搜索以字母开头的项目。谁来帮帮我!

这是我的密码:

代码语言:javascript
复制
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));
    }
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-05 21:52:22

如果您的代码在单词中的任何地方都存在,则它将与键入的字母匹配。如果您希望将仅用于开始的项与键入的字母匹配,jQuery建议使用动态正则表达式,如下所示:

代码语言:javascript
复制
<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中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49119834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档