代码之家  ›  专栏  ›  技术社区  ›  Adrian Schmidt

按瑞典键_、_和_时jquery event.keycode 0

  •  1
  • Adrian Schmidt  · 技术社区  · 15 年前

    我有一个HTML表单,其中有许多文本字段,它们只包含一个字符(想想纵横字谜)。在输入字段中输入字母时,我使用jquery跳转到下一个字母。这很好,除了瑞典字符___¶(其他国际字符也可能受到影响)。

    我将事件监听器绑定到keyup事件,并使用event.keycode和event.which来确定按下的键是否是字母(如果它是任何特殊键,则事件不会被触动)。

    问题是,当我按下“event.keycode”和“event.which”都是0时。当我在Firebug中检查事件对象时,我找不到任何似乎包含键代码的属性。

        var crossword = $('article.crossword');
    
        crossword.bind('keyup', function(event) {
            var target = $(event.target, crossword);
    
            if (target.hasClass('crossword_letter_input')) {
                var pressedKey = event.which ? event.which : event.keyCode;
                var target_value = target.val();
                var target_tabindex;
    
                // Regular alphanumeric keys have keyCodes between 48 and 90.
                if (pressedKey >= 48 && pressedKey <= 90 && target_value.length) {
                    target_tabindex = parseInt(target.attr('tabindex'));
                    $('input.crossword_letter_input[tabindex=' + (target_tabindex + 1) + ']', crossword).focus();
                }
            }
        });
    

        // å, ä and ö reports keyCode 0 for some reason.
        else if (pressedKey === 0 && target_value.length) {
            target_tabindex = parseInt(target.attr('tabindex'));
            $('input.crossword_letter_input[tabindex=' + (target_tabindex + 1) + ']', crossword).focus();
        }
    

    3 回复  |  直到 11 年前
        1
  •  1
  •   naugtur    15 年前

    <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    </head>
    <body>
    
    <input id="whichkey" value="type something">
    <div id="log"></div>
    <script>$('#whichkey').bind('keypress',function(e){ 
      $('#log').html(e.type + ': ' +  e.which );
    });  </script>
    
    </body></html>
    

    alt==0
    a==97
    ą=261
    
        2
  •  1
  •   Heretic Monkey    15 年前

    event.keyCode event.which . 查看jquery的api文档页面上的示例 event.which ,将显示输入字符的密钥代码。

        3
  •  1
  •   istruble kalyan    15 年前

    您经常提到的字符需要输入两个按键。这确实会使按键检测出现问题。所以,与其关注按下的键,不如直接查看输入字段中的值来查看按下键的副作用如何?

    $('input')
        .bind('keyup', function (e) {
            var t = $(this), // the current input element
                value = t.attr('value'),
                new_value = value.slice(-1); // last char only (if any)
            t.attr('value', new_value);
            t.select(); // highlight the text of current element 
                        // or jump to the next... whatever you want
        })
        // optional select on focus to make things consistent if you .select() above
        .bind('focus', function () { 
            $(this).select(); 
        });