javascript JQuery 自动完成 - 选择第一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8036143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery autocomplete - Select first item
提问by RailsSon
I am using jquery autocomplete which I am populating from a ruby on rails application and I am creating a custom autcomplete like so:
我正在使用 jquery 自动完成功能,我从 Rails 应用程序上的 ruby 中填充它,我正在创建一个自定义的自动完成功能,如下所示:
$.widget( "custom.code_complete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$ul = ul;
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
self._renderItem( ul, item );
});
}
});
$("#r-code").code_complete({
source: "URL",
minLength: 2,
select: function(event, ui) {
$(".button-row").fadeIn();
get_details(ui.item.url);
}
});
I am redirecting a user from another page to the page with the autocomplete form with a parameter in the URL which is a code used for the search, here is the JS to do the search:
我将用户从另一个页面重定向到带有自动完成表单的页面,URL 中有一个参数,这是用于搜索的代码,这里是执行搜索的 JS:
function ac_search(code) {
$("#r-code").val(code);
$("#r-code").code_complete('search', code);
}
This performs the search perfectly and displays the drop down list of results. I am trying to have the script then select the first result in the list. I have tried doing it via a selector:
这将完美地执行搜索并显示结果下拉列表。我试图让脚本然后选择列表中的第一个结果。我试过通过选择器来做到这一点:
$(".ui-menu-item:first a").click();
This finds the correct element in the autocomplete list but when I try and simulate a click it gives this error:
这会在自动完成列表中找到正确的元素,但是当我尝试模拟单击时,它会出现此错误:
TypeError: ui.item is null
Is it possible to programmatically click the first item in the autocomplete results list?
是否可以以编程方式单击自动完成结果列表中的第一项?
Cheers
干杯
Eef
埃夫
回答by aprencai
$( el ).autocomplete({
autoFocus: true
});
回答by Irishka
use autoFocus: true
使用自动对焦:true
$( el ).autocomplete({
autoFocus: true
...
});