2

クイズとなるものを作り始めました。ただし、各質問の後に配列を移動したいと考えています。question_holder div をクリックすると (現時点ではプレース ホルダーが最終的に正解になります)、変数 x は DOUBLING のように見えます。

1、2、4、8 になります。ただし、値を警告すると、実際には 1 ずつ増加します。ただし、正しい質問を提示していないだけで、値が 2 倍になるまですべての質問をトラバースし、この質問をユーザーに提示します。

なぜこれが起こっているのか知っている人はいますか?

function question(q, a, b, c) {
    this.q = q;
    this.a = a;
    this.b = b;
    this.c = c;
}

//all questions//
var q0 = new question("question1", "answer a", "answer b", "answer c")
var q1 = new question("question2", "answer d", "answer e", "answer f")
var q2 = new question("question3", "answer g", "answer h", "answer i")
var q3 = new question("question4", "answer j", "answer k", "answer l")
var q4 = new question("question5", "answer m", "answer n", "answer o")
var q5 = new question("question6", "answer p", "answer q", "answer r")
var q6 = new question("question7", "answer s", "answer t", "answer u")
var q7 = new question("question8", "answer v", "answer w", "answer x")

//array to hold all of the questions
var all_questions = [q0, q1, q2, q3, q4, q5, q6, q7];

/*i want to increment this variable by 1 each
    time time i run the new_Question() function.
    */
var x = 0;

$(document).ready(function () {

    new_Question();

    function new_Question() {
        $("#question_holder").text(all_questions[x].q);

        var answer_holders = $("answer_holder");

        $(".answer_holder").eq(0).text(all_questions[x].a);
        $(".answer_holder").eq(1).text(all_questions[x].b);
        $(".answer_holder").eq(2).text(all_questions[x].c);

        $("#question_holder").click(new_Question);

        x++;
        alert(x);
    }
})
4

2 に答える 2

4

イベント ハンドラー ("new_Question") では、クリックごとにイベント ハンドラーとしてアタッチしています。一度だけ行う必要があるため、その行を関数の外に移動します。

だから、これを動かしてください:

    $("#question_holder").click(new_Question);

「new_Question」関数の終了後 (ただし、「ready」ハンドラー内)

于 2013-02-01T23:20:03.067 に答える
1

@Pointyは正しいです。

ただし、これを処理するもう 1 つの方法は、再度バインドする前にクリックのバインドを解除することです。

function new_Question() {
    $("#question_holder").text(all_questions[x].q);

    var answer_holders = $("answer_holder");

    $(".answer_holder").eq(0).text(all_questions[x].a);
    $(".answer_holder").eq(1).text(all_questions[x].b);
    $(".answer_holder").eq(2).text(all_questions[x].c);
    $("#question_holder").unbind("click").click(new_Question);

    x++;
    alert(x);
}
于 2013-02-01T23:24:23.677 に答える