真假循环数组

时间:2014-02-04 21:20:33

标签: javascript jquery

我正在尝试循环一个数组,以便在显示真或假答案时显示下一个问题。当我点击下一步时,我想隐藏上一个陈述并显示下一个陈述。这是我的一段代码。

<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>

5 个答案:

答案 0 :(得分:2)

jeff_kile的答案是完全正确的,你需要一个计数器来跟踪你在一系列问题中的位置。

为了它的价值,我做了一些评论,希望能让事情更清晰;请注意,这根本不是guru级别的javascript,我故意让它非常简单地演示概念

你可以找到它here

以供参考,代码为:

//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);
  });

使用这个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>

和这个css(只是为了确保选择器工作 - 更新:这些并不是严格要求的,但我在jsfiddle中需要它们。):

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

答案 1 :(得分:1)

你需要一个计数器

$(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;
      }
    });
}

答案 2 :(得分:0)

而不是计数器,使用环形计数器,以避免在最后一个问题之后退出数组(而是再次显示第一个问题)。并且您可以使用IIFE创建隐藏变量以用作计数器,因此无法从click函数外部对其进行修改。要做到这一点,创建一个声明计数器变量的函数并返回另一个使用该变量的函数,然后立即调用外部函数(因此创建/返回内部函数)。请参阅下面的代码 - 声音比实际情况复杂得多。

$(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;
        }
    }());
});

答案 3 :(得分:0)

使用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

答案 4 :(得分:0)

Here is a fiddle I确实使用原型来更轻松地创建问题:

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;
}

现在只需将一个新问题推入数组就可以创建一个问题。

然后剩下的函数显示它们并与用户交互:

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));
});

首先,我宣布一个var'i'来跟踪当前的问题。 UpdateQuestion函数更新您的页面以显示当前问题。

按钮的click事件调用一个函数IsGoodAnswer来检查答案是否正确,如果是,则返回true,否则返回false。

然后将结果传递给ValidateAnswer,告知用户答案是对还是错,增加当前问题并调用UpdateQuestion以显示下一个问题。