如何在javascript按下按钮后继续下一个循环迭代?

时间:2017-06-03 23:40:06

标签: javascript jquery loops

我的代码类似于:

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函数定义了单击按钮时会发生什么,但之后循环继续。我总是留下最后一个问题。

解决此问题的最佳方法是什么?

1 个答案:

答案 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++;
  }
});

<强>演示:

&#13;
&#13;
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;
&#13;
&#13;