javascript JQuery AutoComplete,手动选择第一个搜索项并绑定点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13242669/
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, manually select first searched item and bind click
提问by Giorgi
I want to manually select an item in autocomplete and click it given the value.
我想在自动完成中手动选择一个项目,然后在给定值的情况下单击它。
Following code:
以下代码:
autocompleteitem.autocomplete("option", "autoFocus", true).autocomplete("search", autocompleteitem.val());
autocompleteitem is an object of input that holds the value i want to search for. Now this code successfully selects the first item from drop down but it does not click on it. I do not want to click on it myself i want it to happen somehow in that code.
autocompleteitem 是一个输入对象,它保存我要搜索的值。现在这段代码成功地从下拉列表中选择了第一个项目,但它没有点击它。我不想自己点击它,我希望它以某种方式在该代码中发生。
I tried the following additions to the code above which didnt work:
我尝试对上面的代码添加以下内容,但没有用:
.click(), .select(), .trigger('select'), .find('a').click(), .change()
is there any way i can do it?
有什么办法可以做到吗?
thanks
谢谢
please someone help
请有人帮忙
采纳答案by Amar
Take a look at this jqFAQ.comtopic, this will help you to programatically pick the first matching option for a value and set it into the autocomplete textbox. There are few other autocomplete related faqs too, i think that may be useful for you.
看看这个jqFAQ.com主题,这将帮助您以编程方式选择值的第一个匹配选项并将其设置到自动完成文本框中。还有一些其他与自动完成相关的常见问题解答,我认为这可能对您有用。
回答by Rune Vejen Petersen
If you look at the way the jQuery team does it in their unit testsfor autocomplete, they use something similar to the following code:
如果您查看 jQuery 团队在其自动完成单元测试中执行此操作的方式,他们会使用类似于以下代码的内容:
var downKeyEvent = $.Event("keydown");
downKeyEvent.keyCode = $.ui.keyCode.DOWN; // event for pressing "down" key
var enterKeyEvent = $.Event("keydown");
enterKeyEvent.keyCode = $.ui.keyCode.ENTER; // event for pressing "enter" key
$("#autoComplete").val("item"); // enter text to trigger autocomplete
$("#autoComplete").trigger(downKeyEvent); // First downkey invokes search
$("#autoComplete").trigger(downKeyEvent); // Second downkey highlights first item
$("#autoComplete").trigger(enterKeyEvent); // Enter key selects highlighted item
This plunkshows it working
这个plunk显示它有效