Javascript - 多个按钮的代码几乎相同,但结果却截然不同

时间:2018-04-27 11:48:01

标签: javascript

我正在尝试使用html,css和js构建Simon Game。对于那些不熟悉游戏的人来说,游戏基本上会以随机顺序点亮其按钮,如果玩家能够以相同的顺序按下按钮,则序列将重复并递增1.左右。 >我的代码首先生成按下按钮的顺序,然后相应地开始点亮按钮。绿色和蓝色按钮可以正常工作:它们按顺序点亮并关闭。但红色和黄色按钮不能正常工作。当它们轮到它们时,它们只是重复点亮命令,并且永远不会转到用于关闭它们的setTimeout函数。我会发布我认为代码中出现问题的部分,以及下面代码中的项目链接。非常感谢任何帮助!

//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);
}

Here is a link to the project on codepen.

1 个答案:

答案 0 :(得分:0)

好像忘记了#的jQuery选择器中的audio2。这在尝试在[0]上获取索引undefined时会导致错误,并停止执行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);
}