jQuery Keycode help
How could I ru开发者_开发知识库n a simple function when a key is pressed using jQuery. So for example if a user pressed the 'Q' key which is 81 in JavaScript it would run a function.
$(document).bind('keypress', function(event) {
switch(e.which) {
case 81: {
alert('Q!');
break;
}
}
});
Do you want to do this when you're on a particular textbox, or on a page?
You could do this for the page (Which I suspect is what you want)
$(function(){
$(document).keypress(function(event){
if(e.charCode==81){
callMyFunction();
}
});
});
One approach:
$(window).keydown(
function(e){
if (e.keyCode == 113 || e.keyCode == 81) { // 113 = q, 81 = Q
// do this
}
});
JS Fiddle demo
jQuery API references:
keydown()
精彩评论