【问题标题】:How to move focus on next field when enter is pressed? I tried many approaches but nothing is working按下回车键时如何将焦点移到下一个字段?我尝试了很多方法,但没有任何效果
【发布时间】:2019-11-21 18:27:50
【问题描述】:
 <!DOCTYPE html>

 <html>

 <head>

 <title></title>

 </head>

通过按回车键在表单之间切换的Javascript代码。

 <script type="text/javascript">

 $(document).on('keypress', 'input,select', function (e) {

 if (e.which == 13) {

 e.preventDefault();

 var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']');

    console.log($next.length);

    if (!$next.length) {

        $next = $('[tabIndex=1]');
    }

    $next.focus();
}
});

</script>

<body>

创建表单

    <input type="number" name="" tabindex="1">

    <input type="number" name="" tabindex="2">

    <input type="number" name="" tabindex="3">

    <input type="number" name="" tabindex="4">

</form>

</body>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-

q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

</html>

我尝试了很多方法,在线工作的代码在我的电脑上不工作。

【问题讨论】:

标签: javascript jquery html field enter


【解决方案1】:

您的代码可以运行,但您有一些小错误需要修复。

  • 您的 javascript 代码需要放在 jQuery 脚本之后的页脚中(/body 之前)。
  • js代码需要放在body标签或者head标签中。
  • 需要设置form标签。

这是您的代码,但工作版本:

<!DOCTYPE html>

<html>
<head>
    <title></title>
</head>

<body>
    <form>
        <input type="number" name="" tabindex="1">
        <input type="number" name="" tabindex="2">
        <input type="number" name="" tabindex="3">
        <input type="number" name="" tabindex="4">
    </form>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

    <script type="text/javascript">
        $(document).on('keypress', 'input,select', function (e) {
            if (e.which == 13) {
                e.preventDefault();
                var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']');
                console.log($next.length);
                if (!$next.length) {
                    $next = $('[tabIndex=1]');
                }
                $next.focus();
            }
        });
    </script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多