我是javascript的新手,并且正在尝试构建某种内存游戏。
游戏运行良好,直到用户在卡上单击得太快并且“打开”了2张以上的卡为止。
单击可激活该功能。我试图通过添加一个全局变量来检查该功能是否已经激活,在入口处将其设置为1(函数忙),最后将其设置回0(空闲)。它没有用。
任何想法如何解决呢?
代码是:



var isProcessed =0;

function cardClicked(elCard){
  //check to see if another click is being processed
  if(isProcessed===1){
    return;
  }
  //if function is not already active - set it to "active" and continue
  isProcessed=1;


  //doing all kind of stuff

  //setting function to "free" again
  isProcessed=0;

}

最佳答案

我相信您的代码存在的问题是,当您调用该函数时,它会处理并释放当前正在单击的卡,从而也可以单击其他卡。

一个简单的解决方法是:(我假设在单击两张卡片后,它将“关闭”,而其他卡片可用)



var isProcessed =0;
var selectedPair=[];
function cardClicked(elCard){
  //add to the amount of cards processed
  isProcessed++;
  //If there are two cards "processed" then:
  if(isProcessed===2){
    //reset the amount processed after two cards have been opened
    isProcessed=0;
    //"close" card functionality
    //clear the array of selected cards;
    selectedPair=[];
    return;
  }else{
    //add card to the selectedPair array so we can keep track
    //which two cards to "close" after it resets
    selectedPair.push(elCard);
    //do all kinds of stuff
  }
}

09-12 19:39