如何只执行一次函数?
How can I execute a function only once?
例如我有一个函数
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 分。但问题是,如果我不转到数组中的下一个问题,只是继续单击答案按钮,那么在我决定继续下一个问题之前,我会一直获得尽可能多的分数。我怎样才能解决这个问题,只有一次我才能回答这个问题并且只得到一分。我相信不知何故我需要确保函数 运行 只有一次?
这可能很容易解决,但我是新手,想不出任何东西。
您可以使用一个简单的标志,并在调用函数后将其设置为 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
您还可以在授予更多积分之前检查是否pointAmount > 0
。
例如我有一个函数
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 分。但问题是,如果我不转到数组中的下一个问题,只是继续单击答案按钮,那么在我决定继续下一个问题之前,我会一直获得尽可能多的分数。我怎样才能解决这个问题,只有一次我才能回答这个问题并且只得到一分。我相信不知何故我需要确保函数 运行 只有一次?
这可能很容易解决,但我是新手,想不出任何东西。
您可以使用一个简单的标志,并在调用函数后将其设置为 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
您还可以在授予更多积分之前检查是否pointAmount > 0
。