在Javascript中构建测验应用程序时,我如何将一个问题转换为下一个问题?



我目前正在构建一个测验应用程序,我试图完成的一件事是通过点击"下一个"从一个问题转到下一个问题。按钮。我创建了3个问题,我只能让我的测试从问题1到问题3。所以问题2被跳过了,我不知道为什么。任何帮助将不胜感激!请参阅下面我的代码/代码笔https://codepen.io/Michaelm4100/pen/GRQxNQO?editors=1011

// activeQuestion function to remove / add the active-question to each question 
function activeQuestion(el) {
var que = document.getElementsByClassName('question');
for (var questions of que) {
// console.log(questions)

// removing active-question class 
questions.classList.remove('active-question');
}
questions.classList.add('active-question');
}

var nextButton = document.getElementsByClassName('nxt-btn'); 

for (var buttons of nextButton) 

buttons.addEventListener('click', function(e){
// calling active Question to button event listener 
activeQuestion(e);
})
}

当您执行var questions of que时,questions的最终值是最后一个元素-因此当您在循环完成后执行questions.classList.add('active-question')时,您总是将类添加到最后一个元素。

相反,使用持久索引变量跟踪当前的活动问题。

const questions = document.querySelectorAll('.question');
let activeQuestionIndex = 0;
for (const nextButton of document.getElementsByClassName('nxt-btn')) {
nextButton.addEventListener('click', () => {
questions[activeQuestionIndex].classList.remove('active-question');
activeQuestionIndex++;
questions[activeQuestionIndex]?.classList.add('active-question');
});
}

相关内容

最新更新