Javascript 试图将一个变量增加1,但它';它似乎在翻倍

Javascript 试图将一个变量增加1,但它';它似乎在翻倍,javascript,jquery,Javascript,Jquery,我已经开始做一个测验了。但是,我想在每个问题之后遍历数组。一旦我点击问题_holderdiv(现在的占位符,最终将是正确的答案),变量x似乎加倍了 它是1,2,4,8。然而,当我提醒这个值时,它实际上是在增加1。它只是没有提出正确的问题,它遍历所有的问题,直到它达到它的两倍值,并向用户提出这个问题 有人知道为什么会这样吗 function question(q, a, b, c) { this.q = q; this.a = a; this.b = b; this

我已经开始做一个测验了。但是,我想在每个问题之后遍历数组。一旦我点击问题_holderdiv(现在的占位符,最终将是正确的答案),变量x似乎加倍了

它是1,2,4,8。然而,当我提醒这个值时,它实际上是在增加1。它只是没有提出正确的问题,它遍历所有的问题,直到它达到它的两倍值,并向用户提出这个问题

有人知道为什么会这样吗

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);
    }
})
在事件处理程序(“new_Question”)中,每次单击都将其作为事件处理程序附加。您只需要执行一次,因此将该行移到函数外部

所以,移动这个:

    $("#question_holder").click(new_Question);
在“new_Question”函数结束后(但仍在“ready”处理程序中)执行。Pointy是正确的

处理这个问题的另一种方法是在再次绑定之前取消绑定单击

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

尝试使用
x++=1
而不是
x++
@elclars,这会有什么不同?+1,我没有看到更大的画面,只看了语法。很好:)我删除了我的答案,没有必要编辑它来复制你已经涵盖的内容。我刚刚意识到这一点,现在就对它进行了排序,但非常感谢你的回复和解释,我非常感谢。:)不过我还是推荐@Pointy的方法,只是在你没有遵照他的指示的情况下添加了这个。