javascript 使用 jQuery 在文本框中按 Enter 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22955975/
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
Press the enter key in a text box with jQuery
提问by Marco Prins
How can I mimic pressing the enter button from within a <input>, using jQuery?
如何<input>使用 jQuery模拟从 中按下 Enter 按钮?
In other words, when a <input>(type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?
换句话说,当 a <input>(type text) 处于焦点并按下 Enter 键时,会触发某个事件。如何使用 jQuery 触发该事件?
There is no form being submitted, so .submit()won't work
没有提交表单,所以.submit()不起作用
EDIT
编辑
Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulatethe enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')...or stuff like that is what I'm looking for.
好的,请仔细听,因为我的问题被误解了。当在文本框中按下输入按钮时,我不想触发事件。我想模拟在文本框内按下的输入按钮,并从 jQuery 触发它,从$(document).ready. 所以没有涉及的方法on.('keypress')...或类似的东西是我正在寻找的。
回答by Sridhar R
Use keypressthen check the keycode
使用keypress然后检查密钥代码
Try this
试试这个
$('input').on('keypress', function(e) {
var code = e.keyCode || e.which;
if(code==13){
// Enter pressed... do anything here...
}
});
OR
或者
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
回答by corners
Try this:
试试这个:
$('input').trigger(
jQuery.Event('keydown', { which: 13 })
);

