我正在写一段代码,随机地将屏幕上的一些灯光从红色变为绿色,并等待用户点击对应于点亮的灯光的按键。jquery绑定不工作,而在一个JavaScript递归循环内
当我运行此代码时,您可以按a,d,j或l键并弹出警报。但是,只要我点击开始按钮,就不会识别任何按键。当循环结束时,绑定仍然显示为禁用。我尝试将绑定移动到其他地方,但我没有喜悦。非常感谢您的帮助。
$(function() {
$('#start').bind('click', function() { main(); });
$(document).bind('keypress', function(e) { keyPress(e); });
});
function getRand(val) {
return Math.floor(Math.random()*val)+1;
}
function main() {
preD = new Date;
preDs = preD.getTime();
randTime=Math.floor(Math.random()*1001)+1500;
playSound();
flash();
}
function flash() {
zone = getZone();
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_grn.jpg)");
setTimeout(function() {
$('#r'+zone).css("background-image", "url(images/rea_red.jpg)");
if(cond[1] < 8) {
main();
}
} , 200);
} , randTime);
}
function getZone() {
if(condition==1) {
zone = getRand(2);
if(test[1][zone] < 8) {
test[1][zone] += 1;
cond[1] += 1;
return zone;
} else {
getZone();
}
}
}
function keyPress(e) {
var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if (actualkey=="a" || actualkey=="d" || actualkey=="j" || actualkey=="l") {
dd = new Date;
reat = dd.getTime();
alert(1);
//keypressed[condition][zone]['k']=actualkey;
//keypressed[condition][zone]['t']=(reat-preDs);
}
}
有你把某种在'keyPress'的开始调试代码,以确保它不会被调用所有与该故障是在事件处理程序结合的? – justkt 2011-05-03 17:32:31
你可能给我们一个工作的例子,或者至少一个说明这个问题的简单的jsfiddle吗?看到它在行动将是非常有用的。 – 2011-05-03 17:40:53