【发布时间】:2019-02-07 02:12:33
【问题描述】:
我有一个输入字段,它附加了一个 ajax 数据源自动完成功能。
我有一个用于输入字段的 keyup 处理程序,它查找按下回车键的人,当他们这样做时会触发对搜索按钮的点击,从而 ajax 将一些数据加载到另一个 div 中。
问题是,如果这个人速度很快,键入并按下回车,自动完成仍然会弹出。
我尝试了以下方法:
添加
$('#autocomplete').autocomplete('close')。这不起作用,大概是因为自动完成功能尚未打开。如果我输入,请等待自动完成功能出现,然后按 Enter,它会正确关闭它。添加
$('#autocomplete').autocomplete('destroy')。这行得通,但是如果我回到现场尝试另一个搜索,自动完成功能将不再起作用。
所以我想要的是一种取消任何未决请求并在自动完成功能打开时关闭它的方法,但不会禁用或破坏它。
编辑:代码示例(不是我的真实代码,只是用于演示问题的存根)。文件名是scratch.php
<?php
// Stub for search results
if ($_GET['search'])
{
print "Search results for ".$_GET['search']." here";
exit();
}
// Simulated DB search
if ($_GET['term'])
{
print '[{"label":"A 1"},{"label":"A 2"},{"label":"A 3"},{"label":"A 4"}]';
exit();
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<link type="text/css" href="http://code.jquery.com/ui/1.10.1/themes/redmond/jquery-ui.css" rel="stylesheet" />
<script language='javascript'>
$(document).ready(function() {
$('#searchfor').on('keyup',function(e) {
if (e.which == 13) $('#search').trigger('click');
});
$('#searchfor').autocomplete({
source: "/scratch.php",
minLength: 2,
select: function( event, ui ) {
$('#searchfor').val(ui.item.value);
$('#search').trigger('click');
}
});
$('#search').on('click',function() {
try
{
// Cancel any pending autocompletes without destroying the autocomplete completely here.
// This currently doesn't work
$('#searchfor').autocomplete("close");
}
catch(e)
{
// Do nothing except prevent an error
}
$('#results').load('scratch?search='+encodeURIComponent($('#searchfor').val()));
});
});
</script>
</head>
<input id='searchfor' /> <input id='search' type='button' value='search' />
<div id='results'></div>
</html>
【问题讨论】:
-
请提供代码和/或jsfiddle示例
-
@Dom - 添加了代码 sn-p。我不知道如何用 jsfiddle 模拟服务器端的东西,所以我只是粘贴了一个简化的代码 sn-p 来演示手头的问题。
-
增加延迟并使用disable方法而不是close方法怎么样?
标签: jquery-ui autocomplete jquery-ui-autocomplete