我的代码类似于:
for(i = 0; i < array_of_questions.length; i++){
// call function that gathers necessary data + appends question to screen
// Now it needs to wait until the user presses a button to continue on to the next iteration. Right now it is set up like this:
$("#submit_button").on('click', function() {
//save data
});
}
我现在的问题是它正确调用函数...用于所有迭代。 on click函数定义了单击按钮时会发生什么,但之后循环继续。我总是留下最后一个问题。
解决此问题的最佳方法是什么?
答案 0 :(得分:2)
您不需要在任何循环中附加click
处理程序。
使用全局变量作为数组索引的计数器,并在单击按钮时递增它:
var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;
$("#submit_button").on('click', function() {
//save data
if (counter < array_of_questions.length) {
$("#display").append("<div>" + array_of_questions[counter] + "</div>");
counter++;
}
});
<强>演示:强>
var array_of_questions = ["Question1", "question2", "question3"];
var counter = 0;
$("#submit_button").on('click', function() {
//save data
if (counter < array_of_questions.length) {
$("#display").append("<div>" + array_of_questions[counter] + "</div>");
counter++;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submit_button">Click me!</button>
<div id="display"></div>
&#13;