我正在使用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));
}
});
答案 0 :(得分:0)
如果单词中的任何位置存在,您的代码 将匹配键入的字母。如果您想匹配仅开始的项目键入的字母,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中。