2017-04-19 63 views
0

我从头开始测验,现在我有一次显示所有测验问题。如何将其更改为一次只显示一个问题,以便用户单击“下一步”按钮,显示下一个问题及其选择等等?谢谢。一次显示一个测验项目

HTML

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>State Capitals</title> 
    <script> 
    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 

    for (var i = 0; i < myQuiz.length; i++) { 
     document.write(myQuiz[i].ques + "<br />"); 

     for (var j = 0; j < myQuiz[i].choices.length; j++) { 
     document.write("<input type=radio id=myRadio name=radAnswer>" + myQuiz[i].choices[j] + "<br />"); 
     } 
    } 
    </script> 
</head> 
<body> 
</body> 
</html> 

回答

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元素来代替。

相关问题