简体   繁体   English

真假循环数组

[英]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. jeff_kile的答案是完全正确的,您需要一个计数器来跟踪问题所在的位置。

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 请注意,这根本不是大师级的javascript,我特意使它非常简单,以演示概念

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: 使用此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.): 和这个css(只是为了确保选择器可以正常工作- 更新 :并不是严格要求这些,但我在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. 而且,您可以使用IIFE创建一个隐藏变量以用作计数器,因此无法从click函数外部对其进行修改。 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 使用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. 首先,我声明了一个变量“ i”来跟踪当前问题。 The function UpdateQuestion update your page to show the current question. 函数UpdateQuestion更新您的页面以显示当前问题。

The click event of the button call a function IsGoodAnswer that check if the answer is good, if so return true, else false. 按钮的click事件调用函数IsGoodAnswer,该函数检查答案是否良好,如果是,则返回true,否则返回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. 然后将结果传递给ValidateAnswer,该方法通知用户答案是对还是错,增加当前问题并调用UpdateQuestion以显示下一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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