jQuery在chrome和IE上获取keypress事件

时间:2013-08-13 20:36:13

标签: javascript jquery google-chrome firefox keypress

我遇到问题,在chrome和IE上获取事件“keypress”。 在Firefox上它运作良好。

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/

2 个答案:

答案 0 :(得分:5)

我认为问题在于,不会针对箭头键触发Chrome中的keypress事件,而是会触发keydownkeyup。我相信它对IE来说是一样的。

答案 1 :(得分: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;
    }
}