专注于下一个输入字段时,超过了jQuery最大调用堆栈大小

时间:2019-01-17 14:35:42

标签: javascript jquery html

Newb在这里。

我有一个表格:

<form name="code" action="*" method="post" autocomplete="off">
<input type="text" name="code" maxlength="1" autocomplete="off" class="a">
<input type="text" name="code" maxlength="1" autocomplete="off" class="b">
<input type="text" name="code" maxlength="1" autocomplete="off" class="c">
<input type="text" name="code" maxlength="1" autocomplete="off" class="d">
<input type="text" name="code" maxlength="1" autocomplete="off" class="e">
<input type="text" name="code" maxlength="1" autocomplete="off" class="f last">
<button type="submit" class="full" value="" disabled="disabled"></button>
</form>

我的jQuery是:

$("form").on("keyup change paste focusin", function(e){
    e.preventDefault();

    var a=$(this).find("input[type='text'].a");
    var b=$(this).find("input[type='text'].b");
    var c=$(this).find("input[type='text'].c");
    var d=$(this).find("input[type='text'].d");
    var e=$(this).find("input[type='text'].e");
    var f=$(this).find("input[type='text'].f");

    a.val(a.val().replace(/[^0-9]/g,""));
    b.val(b.val().replace(/[^0-9]/g,""));
    c.val(c.val().replace(/[^0-9]/g,""));
    d.val(d.val().replace(/[^0-9]/g,""));
    e.val(e.val().replace(/[^0-9]/g,""));
    f.val(f.val().replace(/[^0-9]/g,""));

    if (a.val().length == 1) {
        a.next(b).focus();
    }
    if (b.val().length == 1) {
        b.next(c).focus();
    }
    ...

});

我要尝试的是填写字段a后。我想转到字段b,依此类推。

现在发生的情况是,当IF条件被触发时,它将引发Maximum call stack size exceeded错误。

我在这里做什么错了?

还有一种更优雅的方式吗?

1 个答案:

答案 0 :(得分:1)

使用jQuery调用.focus()将导致相关的事件处理程序立即运行,并且由于您是从“ focusin”处理程序内部执行的,因此最终会无限递归。我一直通过在超时时间内执行.focus()操作来解决此问题:

if (a.val().length == 1) {
    setTimeout(function() {
        a.next(b).focus();
    }, 1);
}

即使没有递归问题,也必须在将焦点重定向到另一个元素之前让当前的“焦点”工作完成。