2017-04-19 26 views
0

私はクイズを最初から作成しています。今は、一度にすべてのクイズの質問を表示しています。一度に1つの質問のみを表示するように変更するにはどうすればいいですか?ユーザーが「次へ」ボタンをクリックすると、次の質問とその選択肢などが表示されます。ありがとうございました。一度に1つのクイズの項目を表示する

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要素で作業するべきです。

関連する問題