按下Enter键时如何将焦点移至下一个字段?我尝试了很多方法,但是没有任何效果

 <!DOCTYPE html>

 <html>

 <head>

 <title></title>

 </head>

通过按Enter键在表单之间切换的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>

我尝试了许多方法,但在线工作的代码无法在我的计算机上工作。

bjcjggl06040804 回答:按下Enter键时如何将焦点移至下一个字段?我尝试了很多方法,但是没有任何效果

您的代码有效,但是您需要纠正一些小错误。

  • 您的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>
本文链接:https://www.f2er.com/3055667.html

大家都在问