【问题标题】:jQuery fetch keypress event on chrome and IEjQuery 获取 chrome 和 IE 上的按键事件
【发布时间】:2013-08-13 20:36:12
【问题描述】:

我有一个问题,在 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/

【问题讨论】:

  • 在调用处理程序时您传递$this 而不是仅使用this 是否有原因?
  • 另外请解释“不工作”。您是否在控制台上遇到错误?它应该做什么?它在做什么呢?
  • 试试这个。 jsfiddle.net/R9unv我似乎无法发布答案。

标签: javascript jquery google-chrome firefox keypress


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多