1

2 つのオブジェクトの配列があります。ユーザーがボタンを押すと、特定のオブジェクト プロパティの次の値が表示されるようにしたいと考えています。

これが私の配列です:

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

これは、スクリプトの可能な実装を示す JSFiddleの例です。

グローバル オブジェクトを 1 つだけ使用することをお勧めします。の代わりに
使用します。ここに議論があります。.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 に答える
0

currentQuestion をどこかに保存してから、onclick をインクリメントする必要があります

  var singleQuestion = 0;

  function switchQuestion() {

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

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

 }

現時点では、クリックするたびに0にリセットし、長さに基づいて最初または2番目の質問のみを表示します

于 2013-04-03T14:34:05.407 に答える