我正在尝试使用HTML,CSS和JS构建Simon游戏。对于那些不熟悉游戏的人,基本上游戏以随机顺序点亮其按钮,如果玩家能够按相同顺序按下按钮,则序列将重复并增加1。
我的代码首先生成按下按钮的顺序,然后开始相应地点亮按钮。绿色和蓝色的按钮应尽可能地工作:它们点亮并按顺序关闭。但是红色和黄色的按钮无法正常工作。当轮到他们亮起时,他们只需重复点亮命令,而永远不要转移到旨在将其关闭的Settimeout函数中。我将发布我认为是问题出现问题的一部分,以及下面codepen上的项目的链接。任何帮助都非常感谢!
//random is my array of numbers from 1-4, generated randomly, which
//determines the order of the buttons which the user must match.
//j is a counter that increments to iterate through that array.
if (random[j] == 1){
$('#0').addClass('green-lit');
$('#audio1')[0].play();
litID.push(1);
setTimeout(function(){
$('#0').removeClass('green-lit');
}, off);
}
else if (random[j] == 2) {
//this console log and the following addClass command just repeat forever
console.log('red on');
$('#1').addClass('red-lit');
//this audio never gets played
$('audio2')[0].play();
litID.push(2);
//so I think I can safely presume that the code never reaches this
//setTimeout function
setTimeout(function(){
$('#1').removeClass('red-lit');
console.log('red off');
}, off);
}
这是Codepen上项目的链接。
似乎您忘记了audio2
中的jQuery选择器中的#
。在尝试在undefined
上获得索引[0]
时,这会导致错误,并停止JavaScript执行。像下面的那样修复它:
if (random[j] == 1){
$('#0').addClass('green-lit');
$('#audio1')[0].play();
litID.push(1);
setTimeout(function(){
$('#0').removeClass('green-lit');
}, off);
}
else if (random[j] == 2) {
//this console log and the following addClass command just repeat forever
console.log('red on');
$('#1').addClass('red-lit');
//this audio never gets played
$('#audio2')[0].play(); //fix this line!
litID.push(2);
//so I think I can safely presume that the code never reaches this
//setTimeout function
setTimeout(function(){
$('#1').removeClass('red-lit');
console.log('red off');
}, off);
}