开发者

Jquery-Hot key responds to every key

开发者 https://www.devze.com 2023-03-15 09:05 出处:网络
I have downloaded jquery.hotkeys-0.7.9.js plugin and was trying to provide hot key. on pressingctr+t it should open new url address . i have made this something like this

I have downloaded jquery.hotkeys-0.7.9.js plugin and was trying to provide hot key. on pressing ctr+t it should open new url address . i have made this something like this

 jQuery(document).bind('keypress', 'Ctrl+t',function (evt){ 
  alert('ctrl+t is pressed');
  win开发者_运维知识库dow.location.href = ("${createLink(controller:'trip',action:'create')}");
   return false
 });

But this is not working, it resonds to any key in my keyboard,(even if i press a,b,c etc). What changes i should make so that it should respond to only ctr+t ?? even if i delete the downloaded plugin from js folder the result is same\

jquery version i am using is jquery-1.1.3.1.pack.js


According to the example the project gave, you should do this:

$.hotkeys.add('Ctrl+t', function(){
    alert("haha");
});  

But in Chrome(and maybe some other browsers too), Ctrl+t is the default hot key to open a new tab, I don't know how to overwrite it. So when I test, I replace Ctrl+t to Ctrl+v, and it worked.
fiddle: http://jsfiddle.net/QFT8f/
UPDATE:
This is copied from the source file of hotkey.js:

USAGE:
    $.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');});
    $.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});>
    $.hotkeys.remove('Ctrl+c'); 
    $.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'});


Your code is correct based on the documentation, but the plugin does not work as expected (at least in Firefox). I would ditch the plugin and just handle it based on event attributes.

Here's a fiddle with the plugin installed where you can see the event firing when any key is pressed, and how you would limit to only run certain code when 'Ctrl+t' is pressed. Note: you have to click on the output panel to give it focus for the key events to fire.

JavaScript code:

$(document).bind('keypress', 'Ctrl+t',function (e){
    if(e.which==116 && e.ctrlKey){
        alert('Ctrl+t was pressed');
        return false;
    } else {
        alert('Any other key.  Bad code...BAD!');
    }
    return true;//Pass the event on
});

UPDATE

I had previously added the plugin when I was testing, but it appears like I lost it somewhere when I was fiddling, so the example above works in plain JQuery (I'd make the second parameter the function though). Here's the fiddle with the jquery.hotkeys-0.7.9.min.js resource added with the same code, and for me it throws an "elem.getAttribute is not a function" JavaScript error when run with JQuery 1.6. Another reason to ditch the plugin!

0

精彩评论

暂无评论...
验证码 换一张
取 消