如何使用jquery处理tab键

kan*_*arp 2 javascript jquery

我有一种表单,选项卡上的按键字段应该是焦点旋转清晰的。请看下面的代码。

jsfiddle运行

    $('#e').keyup(function (e) {
        if (e.which === 9)
            $("#a").focus();
    });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type = "text" id = "a" name="a" /><br/>
<input type = "text" id = "b" name="b" /><br/>
<input type = "text" id = "c" name="c" /><br/>
<input type = "text" id = "d" name="d" /><br/>
<input type = "text" id = "e" name="e" /><br/>
Run Code Online (Sandbox Code Playgroud)

当它转到字段“e”时,它直接转到“a”,这是可以的。但它不会在“e”处等待,无需有机会进入“e”字段

请指导我。

Gon*_*ing 5

问题是keyup事件发生在它已经将焦点移动到下一个字段之后。

您需要在keydown事件中执行此操作:

    $('#e').keydown(function (e) {
        if (e.which === 9){
            $("#a").focus();
            e.preventDefault();
        }
    });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type = "text" id = "a" name="a" /><br/>
<input type = "text" id = "b" name="b" /><br/>
<input type = "text" id = "c" name="c" /><br/>
<input type = "text" id = "d" name="d" /><br/>
<input type = "text" id = "e" name="e" /><br/>
Run Code Online (Sandbox Code Playgroud)

原因e.preventDefault(),或者只是return false;需要,是keydown仍会从当前聚焦的控件移动(即从#a#b

如果您希望它更通用,请忘记 ID、使用:last:first选择器

例如

    $('input:last').keydown(function (e) {
        if (e.which === 9){
            $("input:first").focus();
            e.preventDefault();
        }
    });
Run Code Online (Sandbox Code Playgroud)