当焦点位于使用 JavaScript 的按钮上时,如何检测“tab keypress”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3413148/
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 detect "tab keypress" when focus is at a button using JavaScript
提问by Peejay
I'm just wondering if any of you done an onkeypress on a button.
我只是想知道你们中是否有人对按钮进行了onkeypress。
my button is like this:
我的按钮是这样的:
asp:Button ID="btnClear" runat="server" Text="Clear" onkeypress="return goToFirst();"/>
the javascript:
javascript:
function goToFirst(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
alert(charCode);
if (charCode = 9 ) {
document.getElementById('txtFirstName').focus();
document.getElementById('txtFirstName').select();
}
return false;
My goal is to detect the tab keypress on a button and set the focus on the specified textbox when tab is pressed.
我的目标是检测按钮上的选项卡按键,并在按下选项卡时将焦点设置在指定的文本框上。
The problem is that the onkeypress event does not fire when tab key is pressed. other keys like numbers and letters fires the event, but not tab.
问题是按下 tab 键时不会触发 onkeypress 事件。其他键(如数字和字母)会触发该事件,但不会触发 Tab。
Is there a solution to my goal?
我的目标有解决方案吗?
Thanks in advance!
提前致谢!
回答by Reigel
use onkeydown. here's a demo
使用onkeydown. 这是一个演示
<input ID="btnClear" onkeydown="return goToFirst();"/>
.
.
function goToFirst(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
alert(charCode);
if (charCode == 9 ) {
document.getElementById('txtFirstName').focus();
document.getElementById('txtFirstName').select();
}
return false;
};

