现在我有一些问题需要通过我的测验应用程序进行调整。
当用户回答第一个问题时,他可以跳过后续问题。
var usersGuess = -1; //this is the starting value of the userGuess variable
这是因为 userGuess 变量是通过用户猜测时单击的单选按钮的 id 进行更新的,而默认的起始变量只是阻止用户跳过第一个问题。我对如何修复它有一些想法,但不确定如何实现。一种方法是检测是否没有检查任何 radio 输入,然后不加载下一个问题,否则加载它。
当用户返回问题时,之前选中的单选按钮就会消失。我还没想好如何解决这个问题。现在我已将之前的答案保存到一个空数组中,但我认为它无法正常工作。
这里是处理 userGuess 的代码以及它如何与我的下一个按钮的事件监听器交互。
nextButton.addEventListener('click', function() {
//prevent user from skipping questions
if (usersGuess === -1) {
console.log(usersGuess);
alert('You must choose an answer!');
} else {
//if users guess is the id of the correct answer, add one
if (usersGuess == questions[index].correctAnswer) {
userScore += 1;
console.log('Users Score: ' + userScore);
}
//store previous user answers into an array
usersAnswers.push(usersGuess);
if (index + 1 < questions.length) {
index++;
addQuizQuestion(questions[index].question);
addQuizAnswers(questions[index].choices);
} else {
alert('You scored a ' + getPercent() + '%!');
}
}
}, false);
这里还有一个用于测试的 codepen 链接:http://codepen.io/laere/pen/KVwBME
感谢您的帮助!
最佳答案
不要把事情搞得太复杂。这里您所需要的只是当前问题的索引,以及每个问题的 bool 值(或整数,用于点)数组。
您需要做的就是检查当前问题是否已得到解答,如果是,则允许用户继续。
当然,由于这是 Javascript,所有这些都是为了更好的用户体验,仅此而已 - 如果有人想继续下一个问题,他们会的(除非您实现一些服务器端检查/问题加载)。
关于javascript - 防止用户跳过我的测验问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371393/