For example I have a function
例如,我有一个函数
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")
}
}
it the answer is correct id adds 1 point to the total amount of points. But the problem is that if I do not move to the next question in array and just keep clicking the answer button, I keep getting points for as much as I want before I decide to move on to the next question. How could I fix this so that only once I can answer the question and get only one point for it. I believe somehow I need to make sure that the function is ran only once?
它的答案是正确的id加1点到总点数。但问题是,如果我不移到数组中的下一个问题,继续点击答案按钮,在我决定进入下一个问题之前,我就会得到我想要的分数。我怎么能修正这个只有一次我才能回答这个问题并且只得到一点。我认为我需要确保函数只运行一次?
This is probably can be solved pretty easily but I'm new and can't think of anything.
这个问题很容易解决,但我是新手,什么都想不出来。
2 个解决方案
#1
5
You can use a simple flag, and set it to true
once the function was called.
您可以使用一个简单的标志,并在函数被调用后将其设置为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
You can also check whether pointAmount > 0
before awarding any more points.
您还可以在授予更多积分之前检查切入点金额>。
#1
5
You can use a simple flag, and set it to true
once the function was called.
您可以使用一个简单的标志,并在函数被调用后将其设置为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
You can also check whether pointAmount > 0
before awarding any more points.
您还可以在授予更多积分之前检查切入点金额>。