我正在处理一个充满要填写的表单的网站,我需要在按下退出按钮时将焦点移动到下一个输入控件,就像按“tab”一样。 我找到了当 keypressed 为 13 时移动焦点的代码,但这需要获取要关注的元素的 ID
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
我需要一个通用函数,当按键代码为 13“that is enter”时触发按 9“that is tab”的默认事件,当然是在 Javascript 中
最佳答案
这将处理多个输入字段。
这是 jQuery 版本: http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
这是纯javascript版本: http://jsfiddle.net/TnEB5/5/ (您可能希望以不同的方式获得 sibling )
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
关于javascript - 如何使用 javascript 强制 "enter key"充当 "tab key"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10537558/