Jquery fast dynamic binding keyboard events operation function code

  • 2020-03-26 21:29:29
  • OfStack

 
(function($) 
{ 
$.extend({ 

key_fn:[], //Holds the function corresponding to the bound character
key_code:[], //Hold characters
key_bind:function(ch,callback){ 
var KeyCode = {a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90}; 

if(KeyCode.hasOwnProperty(ch)){ 
$.key_fn.push(callback); 
$.key_code.push(ch); 
//The first time you need to add an event
if($.key_fn.length == 1){ 

$(document).keypress(function(e){ 
var e = event || window.event; 
var k = e.keyCode || e.which; 

for(var i =0 ; i < $.key_fn.length ;i++){ 

//-32 is lowercase compatible
if(k-32 == KeyCode[$.key_code[i]] || k == KeyCode[$.key_code[i]] ){ 
log('pressed binded key '+k); 
$.key_fn[i](); 
break; 
} 
} 

}); 
} 
}else 
{ 
alert(' Binding events can only be letters '); 
} 
} 

}); 
})(jQuery); 

It can be used as follows
 
$.key_bind('f',set_table_full_screen); 
$.key_bind('r',reloadthis); 

Sometimes we need to add some shortcuts to the application, each time to write the following code, through key_bin is convenient to bind a certain keyboard and corresponding operation function.
 
$(document).keypress(function(){}) 

Related articles: