最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to retrieve keyCode and charCode from a jQuery event object? - Stack Overflow

programmeradmin4浏览0评论

The javascript event object offers keyCode() and charCode() methods such that charCode() returns 0 for keys that don't cause a character to be displayed like enter, key up, key down, delete, backspace, etc.

I want to check for exactly these characters inside a jQuery keypress event callback, but the jQuery event object doesn't give me access to the mentioned methods.

Can I retrieve the js event object from the jQuery one ?

The javascript event object offers keyCode() and charCode() methods such that charCode() returns 0 for keys that don't cause a character to be displayed like enter, key up, key down, delete, backspace, etc.

I want to check for exactly these characters inside a jQuery keypress event callback, but the jQuery event object doesn't give me access to the mentioned methods.

Can I retrieve the js event object from the jQuery one ?

Share Improve this question edited Nov 28, 2011 at 8:21 Raghuram 52.7k11 gold badges114 silver badges124 bronze badges asked Nov 28, 2011 at 7:44 DaudDaud 7,91718 gold badges78 silver badges124 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4
$('#yourid').bind('keypress', function(e) {
    var keycode= (e.keyCode ? e.keyCode : e.which);
        if(keycode == 13){
                // Enter pressed... do anything here...
        }else if(keycode == 46){// delete

        }else if(keycode == 8){ // backspace

        }
});

Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.

If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.

Key code lists are available all over the internet though here is the heavy lifting done for you without depending on any frameworks...

if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}

function keyPressed(evt)
{
 var e = evt || event;
 var key = e.which || e.keyCode;

 if (!powerKeysEnabled) return;
 if (showmeallcodes) {alert( key); return;}

 switch (key)
 {
  case 77:// M
  alert('m key pressed');
  break;

  case 76://L
  alert('L key pressed');
  break;
 }
}
发布评论

评论列表(0)

  1. 暂无评论