admin管理员组

文章数量:1334342

basicly i need my page to respond to left and right arrow keys. so trying to have the body tag trigger an event- got it working in chrome etc, will do nothing in firefox- tried googling and after 50 different results still no dice. anyone got any ideas?

heres what i have that works with chrome-

body tag calls this script

$(document).ready(adjust());

------------------the javascript

function adjust(){
 $("body").keydown(function(){arrowKey(event.keyCode);});
}

function arrowKey(k){
alert(k);
    if (k==37)
        alert("Left");
    else if (k==39)
        alert("Right");
    else if (k==32)
        alert("space");
}

ive replaced methods with alerts in the function for testing purpose but i need to be able to call different functions based on which arrow is pressed

basicly i need my page to respond to left and right arrow keys. so trying to have the body tag trigger an event- got it working in chrome etc, will do nothing in firefox- tried googling and after 50 different results still no dice. anyone got any ideas?

heres what i have that works with chrome-

body tag calls this script

$(document).ready(adjust());

------------------the javascript

function adjust(){
 $("body").keydown(function(){arrowKey(event.keyCode);});
}

function arrowKey(k){
alert(k);
    if (k==37)
        alert("Left");
    else if (k==39)
        alert("Right");
    else if (k==32)
        alert("space");
}

ive replaced methods with alerts in the function for testing purpose but i need to be able to call different functions based on which arrow is pressed

Share Improve this question edited Apr 19, 2011 at 7:21 S L 14.3k18 gold badges79 silver badges119 bronze badges asked Apr 19, 2011 at 7:13 GazowGazow 1,0792 gold badges11 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Actually it works in chrome even without the "event" because event is a keyword in chrome and it is filled with the last triggered event.

The reason it doesn't work in firefox is because you should assign the event like this:

$(document).keydown(function(event){arrowKey(event.keyCode);});

For some reason "body" does not accept the keydown event. Hope it helps.

$("body").keydown(function( ){arrowKey(event.keyCode);});
                           ^ 

event is missing perhaps

$("body").keydown(function(event){arrowKey(event.keyCode);});

On JSFIDDLE.

Ok Why You don't use JavaScript

window.body.onkeydown=function(evt)
{
arrowKey(evt.keyCode);
}

本文标签: javascriptSet keydown to function with jquery not working in firefoxStack Overflow