我从头开始创建测验,现在我让它同时显示所有测验问题。如何更改它以一次只显示一个问题,以便用户点击"下一步"按钮,下一个问题及其选择显示等等?谢谢。
HTML
data-*
答案 0 :(得分:1)
这就是如何在不改变代码的情况下实现您想要的目标。
var myQuiz = [
{
ques: "What is the capital of California?",
choices: ["Los Angeles", "San Francisco", "Sacramento", "San Diego", "Oakland"],
correctAnswer: "Sacramento"
},
{
ques: "What is the capital of Pennsylvania?",
choices: ["Pittsburgh", "Philadelphia", "Harrisburg", "Erie"],
correctAnswer: "Harrisburg"
},
{
ques: "What is the capital of Florida?",
choices: ["Tallahassee", "Tampa", "Miami", "Jacksonville"],
correctAnswer: "Tallahassee"
},
{
ques: "What is the capital of Georgia?",
choices: ["Augusta", "Atlanta", "Savannah"],
correctAnswer: "Atlanta"
}
]; //end of myQuiz array of objects
var questionIndex = -1; // Not started
function nextQuestion() {
document.body.innerHTML = '';
++questionIndex;
document.write(myQuiz[questionIndex].ques + "<br />");
for (var j=0; j < myQuiz[questionIndex].choices.length; j++) {
document.write("<input type=radio id=myRadio name=radAnswer>" + myQuiz[questionIndex].choices[j] + "<br />");
}
if (questionIndex < (myQuiz.length - 1)) {
var nextButton = document.createElement("input");
nextButton.type = "button";
nextButton.value = "Next question";
nextButton.addEventListener('click', nextQuestion);
document.body.appendChild(nextButton);
}
};
nextQuestion();
但是,请记住,与document.write()
合作不是一个好习惯。我不知道这是一个研究问题还是类似的问题,但你应该使用DOM元素。