1

我有一个问题,在 chrome 和 IE 上获取事件“keypress”。在火狐上运行良好。

function bind_input_keypress ($this) {  
    $($this).bind('input', function() {
        $($this).css('width',$($this).val().length*5.5+20);
    })
    $($this).bind('keypress',function(e) {
        /*  delete last extra... */
        if( e.keyCode == '8' && $($this).val()=='' ) { $('#extras b').remove(); }

        /* arrow up */
        if( e.keyCode == '38' ) {
            console.log('38 pressed');
        }
        /* arrow down */

        if( e.keyCode == '40' ) {
            console.log('40 pressed');
            ad_curr     = $('.ad_selectbox .autocomplete ul li.active');

        }
    });
}
$('input').focus(function(){
    bind_input_keypress($(this));
})

为什么这不适用于 chrome 和 IE?

您也可以在 jsfiddle 上查看它 http://jsfiddle.net/a5M6S/2/

4

2 回答 2

5

我认为问题在于keypressChrome 中的事件不是针对箭头键触发的,而是 keydownkeyup触发的。我相信 IE 也是如此。

于 2013-08-13T20:48:49.683 回答
0
function validateInput(keyPressEvent) {
    if (navigator.appName == "Microsoft Internet Explorer")
        var enteredKey = keyPressEvent.keyCode;
    else if (navigator.appName == "Netscape")
        var enteredKey = keyPressEvent.charCode;
    var enteredChar = String.fromCharCode(enteredKey);
    var retValue = true;
    var optionNumber = document.forms[0].challengeQuestion.selectedIndex;
    try {
        switch (optionNumber) {
            case 0:
                window.alert("You must secure your information with a challenge question and answer!");
                document.forms[0].challengeQuestion.focus();
                break;
            case 1:
            case 2:
            case 3:
                if (!/\D/.test(enteredChar) && !/\W/.test(enteredChar))
                    throw "You can only enter letters into this field.";
                break;
            case 4:
            case 5:
                if (!/\d/.test(enteredChar) && !/\W/.test(enteredChar))
                    throw "You can only enter numbers into this field.";
                break;
        }
    }
    catch(inputError) {
        window.alert(inputError);
        retValue = false;
    }
    finally {
        return retValue;
    }
}
于 2013-11-25T16:51:18.877 回答