javascript 按下回车键时如何转到下一个文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23511535/
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 go to next textbox when enter is pressed?
提问by user3563036
Hi guys I'm learning Javascript and I would like to ask you guys how can I go to the next textbox after inputing text when I press the enter button in the keyboard. thank you
大家好,我正在学习 Javascript,我想问你们,当我按下键盘上的 Enter 按钮时,如何在输入文本后转到下一个文本框。谢谢
回答by Felix
You can use .keyup()
to keep track of when user finish key in a character and e.keyCode
to get which key was pressed, if it's 13
(means enter) then use .focus()
to focus the next textbox element:
您可以使用.keyup()
来跟踪用户何时完成字符e.keyCode
中的键并获取按下了哪个键,如果是13
(表示 enter)则用于.focus()
聚焦下一个文本框元素:
$('input[type="textbox"]').keyup(function(e) {
if(e.keyCode == 13) {
$(this).next().focus();
}
});
回答by Amit Joki
I've developed a plugin to include enter event.
我开发了一个插件来包含输入事件。
(function ($) {
$.fn.enter = function (func) {
this.bind('keypress', function (e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
You can call it like this:
你可以这样称呼它:
$('#input1').enter(function(){ $(this).next().focus(); });
回答by Gary Hayes
You can go to the next field in many ways, as demonstrated by all the answers here, but don't forget to assign the order of what is actually NEXT as well. You can go from field to field with the TAB button, and the layout of your site may not always go in the order you'd expect or want. The solution to this is to add tabindex=""
to your fields as such:
您可以通过多种方式转到下一个字段,如此处所有答案所示,但不要忘记分配实际 NEXT 的顺序。您可以使用 TAB 按钮从一个字段转到另一个字段,并且您网站的布局可能并不总是按照您期望或想要的顺序进行。对此的解决方案是添加tabindex=""
到您的字段中:
<input type="text" tabindex="1" />
<input type="password" tabindex="2" />
<input type="submit" value="Log In" tabindex="3" />