jQuery自动完成UI-我希望它开始搜索onfocus而无需用户输入任何内容

jQuery自动完成UI – 我想开始搜索“onfocus”,并在用户选中或点击进入搜索字段时立即显示选项列表,而无需用户输入任何内容。

默认行为似乎要求用户输入字符或向下箭头以开始滚动并开始搜索并获取值,即使我将所需的字符数设置为零也是如此。


 $(“#contact”)。autocomplete({
    来源:'remote.php',
     minLength:0
 });

谢谢!

比艾美特的答案复杂一点,但……

  • 即使框已包含文本,也会在焦点上弹出列表
  • 单击项目后避免重新弹出列表

这里是:

var closing = false; $('#contact').autocomplete({ source: 'remote.php', minLength: 0, close: function() { // avoid double-pop-up issue closing = true; setTimeout(function() { closing = false; }, 300); } }) .focus(function() { if (!closing) $(this).autocomplete("search"); }); 

我发现这段代码更清晰,特定于元素。

  $().autocomplete({ minLength: 0, delay: 500, source: funcDataLookUp, open: function() { $(this).attr('state', 'open'); }, close: function () { $(this).attr('state', 'closed'); } }).focus(function () { if ($(this).attr('state') != 'open') { $(this).autocomplete("search"); } }); 

尝试使用自动完成function绑定focus

 $("#contact").autocomplete({ source: 'remote.php', minLength: 0 }).bind('focus', function () { $(this).autocomplete("search"); }); 

看看我的样本JSFiddle 。

这个解决方案并不适用于我,因为在选择所需结果后,自动完成结果框会再次弹回。 这是因为.focus方法在close: event之前执行。

另外,根据该答案中的代码,一旦盒子关闭,它就不会打开备份,因为closing变量由于close:而保持为true close:.focus之后执行。

以下代码解决了这两个问题 (请注意, close: event中的变量closing设置为false):

 var closing = false; $(function() {$(".autocomplete").autocomplete({ source: 'remote.php', minLength: 0, open: function(){ closing=true; }, close: function(){ closing = false; } }) .focus(function(){ if ((!closing) && ($(this).val() !== "")){ $(this).autocomplete("search"); } }); }) 
 $("#contact").focus(function() { if ($(this).val().length == 0) { $(this).autocomplete("search"); } }); 

确保您的自动填充的minLength为0。

这个解决方案不适合我,但是这个:

 $('#contact').autocomplete({ source: 'remote.php', minLength: 0 }).focus(function(){ if (this.value == "") $(this).trigger('keydown.autocomplete'); }); 

效果很好(来源: jquery论坛 )

JQUERY实际上建议这种方法

http://api.jqueryui.com/autocomplete/#method-search

 $('.yourclass').autocomplete({ minLength: 0 ,source:['blah','andblahagain'] ,focus: function() { $(this).autocomplete("search", ""); }, }); 

基本上你使用minLength:0和焦点事件搜索“”。