仅迭代一个对象数组一次

时间:2014-07-08 09:11:30

标签: javascript jquery arrays iterated-function

$(document).ready(function() {

allQuestions是对象数组,其作用是为我提供问题(question),答案(choices)和正确答案(correctAnswer)应用

        var allQuestions = [{question: "If you were a super hero what powers would you have?",
            choices: ["a", "b", "c", "d"],
            correctAnswer:0},

            {question: "Do you have a cherished childhood teddybear?",
                choices: ["e", "f", "g", "j"],
                correctAnswer:0},

            {question: "Whats your favourite non-alcoholic drink?",
                choices: ["i", "j", "k", "l"],
                correctAnswer:0},

            {question: "Are you religious?",
                choices: ["m", "n", "o", "p"],
                correctAnswer:0}];

接下来,点击带有#next ID的按钮后,标识为#question 的段落应该使用allQuestions中的下一个问题更改其文字阵列。

真实结果?当我点击下一个按钮时,该函数会迭代所有问题,并且只显示最后一个问题。

我尝试使用stackoverflow中的解决方案,设置var hasLooped但不起作用。

        $('#next').click(function(){
            //var hasLooped = false;
            $.each(allQuestions, function(key){

               // if(!hasLooped) {
                    $('#question').text(allQuestions[key].question);
               // }
               // hasLooped = true;
            })
        })
    });

4 个答案:

答案 0 :(得分:1)

将问题索引保存在变量中,并在单击#next时递增。

写下这个:

$(function () {
    var count = 0,
        len = allQuestions.length;
    $('#next').click(function () {
        if (count < len - 1) {
            count++;
            $('#question').text(allQuestions[count].question);
        } else {
            $(this).remove();
    });
});

fiddle

答案 1 :(得分:0)

你需要将当前问题存储在外部的某个地方并引用它而不是传递给每个函数的密钥,因为它总是遍历所有函数,你会看到最后一个。

var intNum = 1;

$('#next').click(function(){

    $('#question').text(allQuestions[intNum].question);
    intNum++;
});

答案 2 :(得分:0)

var clickCount = 0;
$('#next').click(function(){        
  $('#question').text(allQuestions[clickCount].question);       
  clickCount=(clickCount+1>9)?0:clickCount+1;
});

答案 3 :(得分:0)

如果你不喜欢全局变量,你可以试试这个:

$('#next').click(function(){
    var counter = parseInt($("#next").attr("counter"));
    if (counter>=allQuestions.length){
        alert("No more questions!");
        return;
    }
    $('#question').text(allQuestions[counter].question);
    $("#next").attr("counter",counter+1);
});

DEMO HERE

相关问题