如何使用javascript强制"输入密钥"充当"tab键"?

Heb*_*aah 9 javascript keyevent onkeydown

我正在一个充满要填充的表格的网站上工作,我需要按下退出按钮时焦点移动到下一个输入控件,就像按"标签"一样.我发现当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>
Run Code Online (Sandbox Code Playgroud)

我需要一个通用的功能,当按键代码是13"即输入"触发按下9的默认事件"是标签",当然在Javascript

byg*_*ace 11

这将处理多个输入字段.

这是jQuery版本:http: //jsfiddle.net/TnEB5/3/

$('input').keypress(function(e) {
    if (e.which == 13) {
        $(this).next('input').focus();
        e.preventDefault();
    }
});
Run Code Online (Sandbox Code Playgroud)
<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" />
Run Code Online (Sandbox Code Playgroud)

这是纯粹的javascript版本:http: //jsfiddle.net/TnEB5/5/ (你可能希望以不同的方式获得兄弟姐妹)

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;
}
Run Code Online (Sandbox Code Playgroud)
<input id="Text1" type="text"  />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Run Code Online (Sandbox Code Playgroud)

  • OP没有提到jQuery。 (2认同)

jba*_*bey 2

相反,处理按键并向浏览器返回 false:

http://jsfiddle.net/EeyTL/

<input id="Text1" type="text" />
<input id="Text2" type="text" />

<script type="text/javascript">
    document.getElementById('Text1').onkeypress = function (e) {
        if (e.which === 13) {
            document.getElementById("Text2").focus();
            return false;
        }
    };
</script>
Run Code Online (Sandbox Code Playgroud)