【发布时间】:2015-12-31 01:07:08
【问题描述】:
我想实现文本框自动完成功能。目前我使用 jQuery Autocomplete 但我无法实现与搜索延迟相关的功能;例如,如果我搜索“New”,我将有一个自动完成列表,其中包含 ['New York','New South Memphis' .....] 现在,如果我按“S”并立即按下向下箭头,那么我最终会选择第一个项目,即“纽约”,而不是获得以“新 S”开头的城市的结果。 [触发以“New S”开头的搜索城市的 Web 服务调用] 我想要实现的是阻止向下箭头,直到检索到结果。如果有人可以解释我应该关注什么来实现此功能,或者由于 Web 服务调用的异步性质而无法实现?
$(document).ready(function() {
$("#locations").keydown(function() {
var keyword = $("#locations").val();
var url = 'http://autocomplete.wunderground.com/aq?format=json&cb=myCallbackFn&query=' + keyword;
$.ajax({
type: 'GET',
url: url,
async: true,
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
});
});
});
var myCallbackFn = function(data) {
var cities = [];
for (i = 0; i < data.RESULTS.length; i++) {
if (data.RESULTS[i].type == 'city') {
cities.push(data.RESULTS[i].name);
}
}
$("#locations").autocomplete({
source: cities
}).autocomplete("widget").addClass("fixed-height");
}
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
<script type="text/javascript" src="custom.js"></script>
<style>
.fixed-height {
padding: 1px;
max-height: 200px;
overflow: auto;
}
</style>
</head>
<body>
<div class="ui-widget">
<label for="tags">Autocomplete: </label>
<input id="locations" type="text" size="50"/>
</div>
</body>
</html>
【问题讨论】:
-
您可以尝试将其添加到 keydown 事件侦听器的第一行 $('#locations').autocomplete("destroy");
标签: javascript jquery web-services autocomplete jquery-autocomplete