1

我有一个包含两个对象的数组。当用户按下按钮时,我希望显示特定对象属性的下一个值。

这是我的数组:

var allQuestions = [{
    question: "This is question number one",
    choices: ["one", "two", "three", "four"],
    correctAnswer: "two"
}, {
    question: "This is question number two",
    choices: ["dog", "cat", "bear", "lion"],
    correctAnswer: "bear"
}];

当按下按钮时,我想显示下一个“问题”实例。

这是我切换问题的功能:

function switchQuestion() {

    var singleQuestion = 0;

    if(singleQuestion >= allQuestions.length) {
        singleQuestion == 0;
    } else {
        singleQuestion == ""; // not sure what should go here
    }

    document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;

}
4

4 回答 4

3

您需要将问题索引范围限定在函数之外,每次单击按钮时递增,并在超出数组边界时将其重新分配回 0:

var questionIndex = 0;
function switchQuestion() {
  if(++questionIndex >= allQuestions.length) {
    questionIndex = 0;
  }

  document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;
}
于 2013-04-03T14:32:54.447 回答
2

在这段代码中:

if(singleQuestion >= allQuestions.length) {
        singleQuestion == 0;
    } else {
        singleQuestion == ""; // not sure what should go here
    }

使用=而不是完成分配==

if (singleQuestion >= allQuestions.length) {
    singleQuestion = 0;
} else {
    singleQuestion = singleQuestion + 1; // increment
}

增量也可以通过以下简短形式实现:

singleQuestion++;

整个表达式也可以通过使用模数计算来替换:

singleQuestion = (singleQuestion + 1) % allQuestions.length;

最后,变量 singleQuestion 必须在函数之外定义。

于 2013-04-03T14:32:11.537 回答
0

您需要将 currentQuestion 存储在某处,然后在单击时将其递增

  var singleQuestion = 0;

  function switchQuestion() {

  if(singleQuestion >= allQuestions.length) {
      singleQuestion == 0;
   } else {
    singleQuestion +=1; 
   }

document.getElementById('question').innerHTML = allQuestions[singleQuestion].question;

 }

目前,您将在每次点击时将其重置为 0,并且仅根据长度显示第一个或第二个问题

于 2013-04-03T14:34:05.407 回答
0

这是一个JSFiddle示例,它显示了您的脚本的可能实现。

我建议只使用一个全局对象。
并使用.createElement()而不是.innerHTML(). 这是一个讨论

简而言之:

var myGlobalVar = {
    singleQuestion: 0,
    nextButton: document.getElementById("nextQstBtn"),
    questionHolder: document.getElementById("questionHolder"),
    allQuestions: [qstObjOne, qstObjTwo, qstObjThree],

    switchQuestion: function () {
        myGlobalVar.singleQuestion += 1;
        if (myGlobalVar.singleQuestion === myGlobalVar.allQuestions.length) {
                myGlobalVar.singleQuestion = 0;
        }
        myGlobalVar.showQuestion(myGlobalVar.singleQuestion);
    },
    showQuestion: function (qstNum) {
        // Implementation
    },
    init: function () {
        // Script initialisation
        // Attaching events, etc.
};

myGlobalVar.init();
于 2013-04-03T16:53:09.767 回答