代码之家  ›  专栏  ›  技术社区  ›  Limpuls

如何只执行一次函数?

  •  2
  • Limpuls  · 技术社区  · 7 年前

    例如,我有一个函数

    Question.prototype.checkAnswer = function(answer1, answer2) {
       if (answer1.innerHTML  == this.correctAnswer) {
        console.log("correct");
        players1.moveCharacter = true;
        pointAmount+= 1;
        point.innerHTML = pointAmount;
      } else {
        console.log("nope")
      }
    }
    

    如果答案是正确的,则ID在总点数上加1分。但问题是,如果我不移动到数组中的下一个问题,只需继续单击“答案”按钮,在决定移动到下一个问题之前,我会尽可能多地获得分数。我怎样才能解决这个问题,只有一次我能回答这个问题,并且只得到一分。我相信我需要确保函数只运行一次?

    这可能很容易解决,但我是新来的,什么都想不起来。

    2 回复  |  直到 7 年前
        1
  •  5
  •   Marcos Casagrande    7 年前

    您可以使用一个简单的标志,并将其设置为 true 一旦函数被调用。

    function Question() {}
    
    Question.prototype.checkAnswer = function(answer1, answer2) {
       
      if(this.answerChecked)
        return; // If answer was already checked, leave.
      
      this.answerChecked = true;
     
      // The rest of your code
      console.log('Run');
    }
    
    const question = new Question();
    
    question.checkAnswer('yes', 'no');
    question.checkAnswer('again', 'no'); // This will do nothing
        2
  •  1
  •   hologram    7 年前

    你也可以检查 pointAmount > 0 在授予更多积分之前。

    推荐文章