Javascript JQuery 模拟输入字段上的按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6124692/
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 simulating keypress event on an input field
提问by Masiar
I have an input field which is dynamically filled with some AJAX, and once it's filled I would like to have JavaScript to automatically press "Enter" (key event 13) on that input inducing another function, which is hidden to me, to trigger.
我有一个输入字段,它用一些 AJAX 动态填充,一旦它被填充,我想让 JavaScript 在该输入上自动按下“Enter”(键事件 13),从而引发另一个对我隐藏的函数来触发。
Would it be possible with jQuery? I have this code right now, which is not working:
用jQuery可以吗?我现在有这个代码,但它不起作用:
$('#myInputId').focus().trigger({ type : 'keypress', which : 13 });
$('#myInputId').focus().trigger({ type : 'keypress', which : 13 });
Do you have any clue on what am I doing wrong?
你对我做错了什么有任何线索吗?
Thanks,
谢谢,
Masiar
马西亚尔
回答by Felix Kling
You can create an event object:
您可以创建一个 事件对象:
$('#myInputId').trigger(jQuery.Event('keypress', { keycode: 13 }));
回答by John
Hi you could try use the change event for when the input area changes :
嗨,您可以尝试在输入区域更改时使用更改事件:
$('#myInputId').change(function(){
$('#myInputId').focus().trigger({ type : 'keypress', which : 13 });
});
回答by Masoud Darvishian
On Keypress Enter
:
在按键上Enter
:
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in somewhere');
}
});