3

在空输入上按退格键时如何返回上一个输入?

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

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

JSFIDDLE:http: //jsfiddle.net/EwYKX/

4

2 回答 2

4

The input event will not fire if the element already has empty value because there's no value change.

A keyup check for backspace press should suffice. Assuming the input elements are always direct siblings as in your example:

$('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();
    }
});

Fiddle

I've added a propertychange listener as fallback for old IE, but you can remove it if you don't feel like using this ugly hack to support old IE. Also I've swapped .select() by .focus() so that it doesn't select the entire field upon focusing, but that is up to you too. =]

The e.which === 8 check is so that it only moves to the previous field by pressing the backspace key, but in case you'd like to move to the previous input even if the user erases the field value through other means (e.g. delete key or cut/delete context menu) you can remove the e.which === 8 too, though that wouldn't make much sense UX-wise imho.

于 2013-04-19T23:01:32.980 回答
0

try this

        $('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();
           }
        });
于 2013-04-19T23:04:54.100 回答