2016-11-16 3 views
0

私は値を持つオブジェクトを参照するクイズアプリを書いていますが、これは初心者のコードですが、すべてうまくいきます。具体的には、ユーザーが「次の質問」ボタンをクリックすると、最初の質問を2番目の質問に置き換えます。しかし、私のnextQuestion()はオブジェクト内の変数を増やしていますが、残りのコードでは変わりません。jqueryを使用して別の関数が使用するオブジェクト値を更新する関数を1つ使用しますか?

var quiz = { //the questions, you get the idea// 
 
    correctCount: 0, 
 
    currentQuestion: 0, //THIS IS WHAT I WANT TO UPDATE IN EACH ITERATION 
 
    questions: [{ 
 
    question: "Question 1?", 
 
    answers: ["A", "B", "C", "D"], 
 
    correct: "A" 
 
    }, { 
 
    question: "Question 2?", 
 
    answers: ["A", "B", "C", "D"], 
 
    correct: "C" 
 
    }] 
 
}; 
 

 
$(document).ready(function() { 
 
    $(".question").hide(); 
 

 
    //jquery event delegation 
 
    function generateQuestion() { 
 
    $("div.question").prepend(quiz.questions[quiz.currentQuestion].question); 
 
    var answerList = quiz.questions[quiz.currentQuestion].answers; 
 
    console.log(answerList); 
 
    for (var i = 0; i < answerList.length; i++) { 
 
     $("ul").append("<li>" + answerList[i] + "</li>"); 
 
    } 
 
    console.log(quiz.currentQuestion); 
 
    } 
 

 
    function questionCheck() { 
 
    $(".question-space").on('click', 'li', function(e) { // 
 
     e.preventDefault(); 
 
     console.log($(this).val()); 
 
     if ($(this).text() === quiz.questions[quiz.currentQuestion].correct) { 
 
     alert("Yes! The correct answer was " + quiz.questions[quiz.currentQuestion].correct + "!"); 
 
     quiz.correctCount += 1; 
 
     $(".numCorrect").text(quiz.correctCount); 
 
     } else { 
 
     alert("Sorry! The correct answer was " + quiz.questions[quiz.currentQuestion].correct + "!"); 
 
     } 
 
    }); 
 
    } 
 

 
    function nextQuestion() { 
 
    $(".next-question").on('click', function(e) { 
 
     e.preventDefault(); 
 
     quiz.currentQuestion += 1; 
 
     console.log(quiz.currentQuestion); 
 
    }); 
 
    } 
 

 

 
    //Event listeners 
 
    $(".start-quiz").click((function() { 
 
    $(".box").hide(); 
 
    $("div.question").show(); 
 
    generateQuestion(); 
 
    questionCheck(); 
 
    nextQuestion(); 
 
    })); 
 

 
});

+0

あなたは 'questions:'配列の最後に ']'を、 'quiz'オブジェクトの最後に'} 'がありません。 – Barmar

+0

'quiz.questions [* * quiz.currentQuestion * *]はどういう意味ですか?このように '*'を使うことはできません。 – Barmar

+0

これがコードの強調表示であると思われる場合は、SOのコードブロック内にマークアップを行うことはできません。 – Barmar

答えて

0

[OK]をクリックします。私は機能には何もレンダリングされませんでした実現した後、それを解決することができました:

function nextQuestion() { 
    $(".next-question").on('click', function(e) { 
    e.preventDefault(); 
    quiz.currentQuestion += 1; 
    console.log(quiz.currentQuestion); 
    $("div.question").empty(); 
    generateQuestion(); 
    questionCheck(); 
    }); 
} 

私が原因の子孫のすべてを取り出しempty()方法の生成質問機能の私のjQueryの一部を変更するために必要な、しかし、少なくともこれは機能しています。

関連する問題