如何在 jquery 自动完成中绑定按键事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16250696/
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
How to bind keypress event in jquery autocomplete?
提问by Anshul
As you can see in http://jsfiddle.net/hn838/4/'click' is working fine for autofiller, But I want to trigger same code on enter key keypress also, but it is not working for me. My code is here for both. Click :
正如您在http://jsfiddle.net/hn838/4/中看到的那样,“click”对于自动填充程序工作正常,但我也想在输入键时触发相同的代码,但它对我不起作用。我的代码都在这里。点击 :
$('.ui-autocomplete').on('click', '.ui-menu-item', function(){
$('.college').trigger('click');
});
Keyprss :
按键:
$('.ui-autocomplete').on('keypress', '.ui-menu-item', function(e){
if (e.which == 13) {
e.preventDefault();
$('.college').trigger('click');
}
});
I want $('.college').trigger('click');
execution on click
and enter keypress
. click is working fine but keypress in not working.any clue ?
我想 $('.college').trigger('click');
执行click
并输入keypress
. 点击工作正常,但按键不起作用。有什么线索吗?
回答by louisbros
Rather than binding to key events, you could add a function to the selectevent:
您可以向select事件添加一个函数,而不是绑定到键事件:
select: function(){
$('.college').trigger('click');
}
That way it'd only trigger when the user actually selected the autocomplete value.
这样它只会在用户实际选择自动完成值时触发。
回答by Eli
There is no class ui-autocomplete
inside your fiddle. So I assume it looks like this:
ui-autocomplete
你的小提琴里面没有课。所以我假设它看起来像这样:
<input type = 'text' class = 'search ui-autocomplete' />
and also there is no class ui-menu-item
in your fiddle, so you should do like this:
并且ui-menu-item
您的小提琴中也没有课程,所以您应该这样做:
$('.ui-autocomplete').on('keypress', function(e){
if (e.which == 13) {
e.preventDefault();
$('.college').trigger('click');
}
});
If you want to use the class that automatically generated from jQuery UI, you can do:
如果你想使用从 jQuery UI 自动生成的类,你可以这样做:
$('.ui-autocomplete-input').on('keypress', function(e){
if (e.which == 13) {
e.preventDefault();
$('.college').trigger('click');
}
});