简体   繁体   中英

Targeting correct answers with button click in trivia game

I am trying to code out a trivia game. I figured out how to display the question with the appropriate answers. Now, I have to figure out if the user clicked the correct answer or not. I think I need to use an if/else statement, but I am not entirely sure which steps I need to take next. Here is the link to the live site-- (I know there are some styling things left to do.

https://alyciamriley.github.io/Trivia-game-easier/

And here is my JS code-

     window.onload = function () {


    var intervalId
    var timer = 10;
    var questionArray = [{

            question: 'Who recorded the original version of the song "Hound Dog"?',
            answers: ['Willa Mae "Big Mama" Thornton', 'Elvis Presley', 'Carl Perkins', 'Chuck Berry', 'Miley Cyrus'],
            correctAnswer: 'Willa Mae "Big Mama" Thornton',
}, {

            question: 'Who was marketed by her record company as the "female Elvis"?',
            answers: ['Wanda Jackson', 'Janis Martin', 'Patsy Cline', 'Diana Ross', 'Miley Cyrus'],
            correctAnswer: 'Janis Martin',
}, {

            question: 'Who sang the 1957 song Whole Lotta Shakin Goin On?',
            answers: ['Elvis Presley', 'Jerry Lee Lewis', 'Gene Vincent', 'Buddy Holly', 'Miley Cyrus'],
            correctAnswer: 'Jerry Lee Lewis',
}, {

            question: '"Rebel-Rouser", "Cannonball", and "Because They Are Young" were all hits by which artist?',
            answers: ['The Big Bopper', 'Jerry Lee Lewis', 'Gene Vincent', 'Duane Eddy', 'Miley Cyrus'],
            correctAnswer: 'Duane Eddy',
},

        {

            question: 'Who spent three weeks at No.1 in 1957 with “That’ll be the Day”?',
            answers: ['Buddy Holly', 'June Carter', 'Little Richard', 'Fats Domino', 'Miley Cyrus'],
            correctAnswer: 'Buddy Holly',
}];





    //Start  button starts game
    //clearing the content works.  Do not touch it. 
    $("#startGame").on("click", function () {
        $("#startGame").replaceWith();
        startTimer();
        decrement();
        firstQuestion();
        //renderButtons();
    })

    //this is your timer.  It is working.  Do not touch it. 
    function startTimer() {
        intervalId = setInterval(decrement, 1000);
    }

    function decrement() {
        timer--;
        $("#countdown").html("<span>" + timer + "<span>");

        if (timer === 0) {
            stopTimer();
        }
    }

    function stopTimer() {
        clearInterval(intervalId);
        nextQuestion();

    }

    function firstQuestion() {
        var randomQuestion = questionArray[Math.floor(Math.random() * questionArray.length)];
        $("#question-display").html(JSON.stringify(randomQuestion.question));
        renderButtons(randomQuestion);
    }

    function renderButtons(randomQuestion) {
        //Cleared button div of any newly created buttons
        $("#answer-display").empty();
        //dynamically generates buttons for each answer
        for (var i = 0; i < randomQuestion.answers.length; i++) {
            var a = $("<button>");
            //adds class to the button
            a.addClass("btn-answer");
            //adds a data attribute
            a.attr("data-name", randomQuestion.answers[i]);
            //labels button
            a.text(randomQuestion.answers[i]);
            //adds button to the button view div
            $("#answer-display").append(a);
        }

    }

    $("#answer-display").on("click", function(){
        console.log("clicked");


        });   


    };

First of all you need to set the click handler for the buttons. More information about events can be found here http://api.jquery.com/on/ .

We will access the values needed to check the result using data(). More information here http://api.jquery.com/data/

One way of achieving this using a delegated event is:

//attach click to all elements with class btn-answer inside element with id answer display
$("#answer-display").on("click", ".btn-answer", function(){
       //get answer from clicked element
       var answer = $(this).data("answer");
       //get correct answer from parent element
       var correctAnswer = $("#answer-display").data("answer");
       // correct logic
       if (answer == correctAnswer) {
           console.log("correct!!!");
       }else {
           console.log("wrong!!!");
       }
}); 

In order this code to work you have to make two other changes to your code: after

$("#answer-display").empty();

add this

$("#answer-display").data("answer", randomQuestion.correctAnswer);

so you can access the correct answer in the click handler part

and also change this:

a.attr("data-name", randomQuestion.answers[i]);

to this

a.data("name", randomQuestion.answers[i]);

to be more consistent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM