Skip to content

Instantly share code, notes, and snippets.

@CrBoy
Created May 12, 2013 08:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CrBoy/5562852 to your computer and use it in GitHub Desktop.
Save CrBoy/5562852 to your computer and use it in GitHub Desktop.
可以讓 jQuery 綁定鍵盤事件時指定只對特定按鍵作用的小程式。 使用方式: 1. 引入 jQuery 後,引入此 js 檔 2. 在綁定事件時這樣寫: $(this).keypress(13)(handler); 其中 $(this) 可代換成任何 jQuery 物件,handler 則是一般用於事件的 callback function。在此範例中,僅有當按下的按鍵為 enter 時, handler 才會作用。
var extend_keyboard_event_with_keycode = function(original_event_name) {
var $fn_original = $.fn[original_event_name];
var keyboard_event_function_wrapper = function(keycodes, handler) {
return function(e) {
if(keycodes.indexOf(e.which) != -1)
return handler(e);
}
}
var wrap_the_function_in = function(keycodes, args) {
// version: key*(handler)
if(typeof arg[0] == 'function')
args[0] = keyboard_event_function_wrapper(keycodes, args[0]);
// version: key*(data, handler)
if(typeof arg[1] == 'function')
args[1] = keyboard_event_function_wrapper(keycodes, args[1]);
return args;
}
$.fn[original_event_name] = function(){
var $object = this,
keycodes = [],
args = [];
// version: key*()
if(arguments.length == 0)
return $fn_original.apply($object);
for(var n=arguments.length; n-- > 0; )
args.unshift(arguments[n]);
var num;
while( num=args.shift() ){
if(typeof num === 'number')
keycodes.push(num);
else{
args.unshift(num);
return $fn_original.apply($object, wrap_the_function_in(keycodes, args));
}
}
return function(){
return $fn_original.apply($object, wrap_the_function_in(keycodes, arguments));
}
}
}
extend_keyboard_event_with_keycode('keypress');
extend_keyboard_event_with_keycode('keyup');
extend_keyboard_event_with_keycode('keydown');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment