【问题标题】:Autocomplete Improvement自动完成改进
【发布时间】: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


【解决方案1】:

完成此操作的一种方法是在针对建议的新 GET 请求被触发时删除所有自动完成建议,或者设置一个标志以在请求解决之前忽略向下箭头按键。

【讨论】:

  • 有没有可能我可以使用 Promise 等到请求解决?
  • 是的——这就是承诺的目的。
猜你喜欢
  • 2011-08-21
  • 1970-01-01
  • 2011-10-14
  • 2013-08-28
  • 1970-01-01
  • 2015-08-20
  • 2021-07-13
  • 2020-12-18
  • 2012-06-12
相关资源
最近更新 更多