我已经开始制作一个测验了。但是,我希望在每个问题之后移动数组。一旦我点击了question_holder div(现在的占位符,最终将是正确的答案),变量x似乎是DOUBLING。
它是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);
}
})
答案 0 :(得分:4)
在您的事件处理程序(“new_Question”)中,您将其作为每次单击的事件处理程序附加。您只需要执行一次,因此将该行移动到函数外部。
所以,请移动:
$("#question_holder").click(new_Question);
在答案 1 :(得分:1)
@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);
}