问题描述
我被卡住了,不知道如何修复我的代码。
这是我的代码:
const updatescore = (isCorrect) => {
// Update Game Variables
if (isCorrect === true) {
counter++
score += 100;
}
}
// Reset Styling
const resetLoadedQuestionStyling = (isCorrect) => {
questionScreen.style.display = 'none';
answerArr.forEach(answer => {
answer.classList.remove('correct');
answer.classList.remove('wrong');
answer.classList.remove('disable');
updatescore(isCorrect)
});
}
const styleAnswer = (div,isCorrect) => {
if (isCorrect === true) {
div.classList.add('correct');
} else {
div.classList.add('wrong');
for (let i = 0; i < answerArr.length; i++) {
if (i === currentQuestion.correct) {
answerArr[i].classList.add('correct');
}
}
}
// Prevent Second Check
answerArr.forEach(answer => {
answer.classList.add('disable');
});
// Reset Styling
setTimeout(() => {
resetLoadedQuestionStyling(isCorrect);
},3000);
}
const checkAnswer = (div,index) => {
const userChoice = index;
// Default Answer State
let isCorrect = false;
if (userChoice === currentQuestion.correct) {
isCorrect = true;
}
styleAnswer(div,isCorrect);
}
answerArr.forEach((div,index) => {
div.addEventListener('click',() => {
checkAnswer(div,index);
});
});
我有一个由 4 个 div 组成的数组。 (answerArr
)。
我正在将 div 的索引与存储在另一个对象数组中的 (currentQuestion.correct
) 进行比较。
到目前为止一切都很好。 当我更新计数器和分数时出现问题。
我确切地知道为什么:
answerArr.forEach((div,index);
});
});
这将运行我的 checkAnswer
函数四次......所以我的分数增加了四次,而不是一次。 (例如:计数器 = 4,一次运行后得分 = 400。)
一个简单的解决方法是删除在事件侦听器中调用的函数并将其直接放入其中。
示例:
answerArr.forEach((div,checkAnswer);
});
但是我无法传递参数(div 和 index)以正确移动到其他函数。
提前谢谢大家!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)