Javascript 使用jQuery选择上一个输入

Javascript 使用jQuery选择上一个输入,javascript,jquery,Javascript,Jquery,在空输入上单击backspace时,如何返回到以前的输入 $('input').bind('input', function() { if (this.value.length >= $(this).attr('maxlength')) { $(this).next().select(); } if (this.value.length == 0) { $(this).prev().s

在空输入上单击backspace时,如何返回到以前的输入

    $('input').bind('input', function() {
        if (this.value.length >= $(this).attr('maxlength')) {
            $(this).next().select();
        }

        if (this.value.length == 0) {
            $(this).prev().select();
        }
    });

jsiddle:

如果元素已经有空值,则不会触发
输入
事件,因为没有值更改

按下
keyup
键检查退格键就足够了。假设输入元素始终是直接同级元素,如示例中所示:

$('input').on('input propertychange', function() {
    if (this.value.length >= this.maxLength) {
        $(this).next().focus();
    }
}).keyup(function(e) {
    if (e.which === 8 && !this.value) {
        $(this).prev().focus();
    }
});

我已经添加了一个
propertychange
监听器作为旧IE的后备,但是如果你不想使用这个丑陋的黑客来支持旧IE,你可以删除它。我还交换了
.select()
by
.focus()
,这样它在聚焦时不会选择整个字段,但这也取决于你<代码>=]

e.which==8
复选框的作用是,它只能通过按backspace键移动到上一个字段,但如果您想移动到上一个输入,即使用户通过其他方式(例如删除键或剪切/删除上下文菜单)擦除字段值,也可以删除
e.which==8
,尽管这对UX智能imho没有多大意义。

试试这个

        $('input').bind('input, keydown', function (e) {
           if (this.value.length >= $(this).attr('maxlength')) {
              $(this).next().select();
           }

           if (this.value.length == 0 && e.keyCode == 8) {
              $(this).prev().focus();
           }
        });

你可能不应该这样做。这些类型的自动选项卡字段经常出错。例如,尝试在此处将字母“a”更改为“b”:只需将其全部设置为一个字段。您不希望
focus()
,而不是
select()
?信息量很大。这不仅完成了工作,我还从这样一个描述性的回答中学到了很多。谢谢。我相信你想在这里使用