简体   繁体   中英

True and False looping array

I'm trying to loop over an array to display the next question when either the true or false answer is shown. When I click next, I'll like to hide the previous statement and show the next. Here is my piece of code.

<body>    

<div class="row">
  <div class="large-3 medium-3 small-3 small-centered columns">
    <div class="content"></div>
    <button class="true">True</button>
    <button class="false">False</button>
  </div>
</div>

<script>
  $(document).ready(function(){
    var questions = ['The Earth is round', 'The sun is yellow', 'Dogs are reptiles'];
    var answerTrue = ['You Got It!'];
    var answerFalse = ['Dogs are mamals'];

    $('button.true').click(function(){
      $('.content').text(questions[1]);
    });

  });
</script>

jeff_kile's answer is totally correct, you need a counter to keep track of where in the array of questions you are.

For what it's worth, I did a jsfiddle with some comments that hopefully will make things clearer; note this is not guru-level javascript at all, I have deliberately kept it very simple to demonstrate the concepts

You can find it here

and for reference, the code is:

//setup array of questions with text, correct answer and what to display if the user gives
//and incorrect answer
var questions=[
    {text:'The Earth is Round',answer:true,note:'It\'s not flat'},
    {text:'The sun is yellow',answer:true,note:'no really it is'},
    {text:'Dogs are reptiles',answer:false,note:'What planet are you from?'}
];

//question array index
var index=0;

//helper function to display the content
var setContent=function(text)
{
    $(".content").text(text);
}

//helper function to show the current question
 var showQuestion=function(index)
    {
      question=questions[index];
       setContent(question.text);
    }
//helper function that checks if the user supplied answer is correct
 //and if so eother advances the question index or ends the game
 //otherwise, displays the question note.
var checkAnswer=function(userAnswer)
{
    question=questions[index];
     if (question.answer==userAnswer)
        {
            index++;
            if (index>=questions.length)
            {
                setContent("Thanks for playing");
            }
            else
            {
            showQuestion(index);
            }
        }
        else
        {
          setContent(question.note);
        }
}

//wireup clicks to send the answer for the current question to the answer check function
//and kicks off the game with question 0
$(document).ready(function(){

    $(".true").click(function(){
       checkAnswer(true);  
    });    
    $(".false").click(function(){
     checkAnswer(false); 
    });
       showQuestion(index);
  });

using this html:

 <div class="row">
  <div class="large-3 medium-3 small-3 small-centered columns">
    <div class="content"></div>
    <button class="true">True</button>
    <button class="false">False</button>
  </div>
</div>

and this css (just to make sure the selectors work - Update : these are not strictly required, but I needed them in jsfiddle.):

.content:{}
.true:{}
.false:{}

You need a counter

$(document).ready(function()) {
    var questions = ['The Earth is round', 'The sun is yellow', 'Dogs are reptiles'];
    var answerTrue = ['You Got It!'];
    var answerFalse = ['Dogs are mammals'];
    var counter = 0;

    $('button.true').click(function(){       
      if(counter < questions.length) {
          $('.content').text(questions[counter]);
          counter = counter + 1;
      }
    });
}

instead of a counter, use a ring-counter, to avoid stepping out of the array after the last question (instead, the first one is shown again). And you can use a IIFE to create a hidden variable to use as a counter, so it cannot be modified from outside the click function. TO do that, create a function that declarates the counter variable and returns another function that uses that variable, then immediately call the outer functio (so the inner one is created/returned). See code below - sound's a lot more complicated than it actually is.

$(function () {
    var questions = ['The Earth is round', 'The sun is yellow', 'Dogs are reptiles'];
    var answerTrue = ['You Got It!'];
    var answerFalse = ['Dogs are mammals'];

    $('button.true').click(function () {
        var counter = 0;
        return function () {
            $('.content').text(questions[counter]);
            counter = ++counter % questions.length;
        }
    }());
});

Use nested arrays

 $(document).ready(function () {
     var questions = [
         ["Q1?", "true", "Noooo, beer!"],
         ["Q2?", "false", "Impossible!"],
         ["Q3?", "true", "It's more like a thing"],
         ["Q4?", "false", "Yes, but more like no"]
     ];

     var i = 0;

     $('.content').text(questions[i][0]);

     $('button').click(function () {
         var target = event.target;

         if ($(target).attr('class') == questions[i][1]) {
             i++;
             $('.content').text(questions[i][0]);
         }
         else alert(questions[i][2]);
     });
 });

Fiddle

Here is a fiddle I did using prototype to make it easier to create question:

var listQuestions = new Array();
listQuestions.push(new Question("The Earth is round", true));
listQuestions.push(new Question("The sun is yellow", true));
listQuestions.push(new Question("Dogs are reptiles", false));

function Question(text, ans) {
    this.text = text;
    this.ans = ans;
}

Question.prototype.IsGoodAnswer = function (ans) {
    return this.ans === ans;
}

Question.prototype.GetQuestion = function() {
     return this.text;
}

Now it's possible to create a question simply by pushing a new one into the array.

Then the rest of the function to show them and interact with the user:

var i = 0;

function UpdateQuestion() {
    if (i < listQuestions.length) {
        $('.content').text(i + listQuestions[i].GetQuestion());
    } else {
        $('.content').text("No more questions");
    }
}

UpdateQuestion();

function ValidateAnswer(isCorrect) {
    if (isCorrect) alert("Good answer!");
    else alert("Wrong answer :(");
    i++;
    UpdateQuestion();
}

$('button.true').click(function () {
    ValidateAnswer(listQuestions[i].IsGoodAnswer(true));
});

$('button.false').click(function () {
    ValidateAnswer(listQuestions[i].IsGoodAnswer(false));
});

First I declared a var 'i' to keep track of the current question. The function UpdateQuestion update your page to show the current question.

The click event of the button call a function IsGoodAnswer that check if the answer is good, if so return true, else false.

Then the result is passed to ValidateAnswer that inform the user if the answer is right or wrong, increment the current question and call UpdateQuestion to show the next one.

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