简体   繁体   English

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

[英]How to continue to next loop iteration only after a button press in javascript?

I have code similar to this: 我有与此类似的代码:

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

        });
}

My problem now is that it calls the function correctly... for all of the iterations. 我现在的问题是,对于所有迭代,它正确地调用了函数。 The on click function defines what would happen if the button was clicked but the loop continues after that. 单击功能定义了单击按钮后会发生什么,但此后循环继续。 I'm always left with the last question displayed. 我总是留下最后一个显示的问题。

What is the best approach to fix this? 解决此问题的最佳方法是什么?

You don't need to attach the click handler in any loop. 您无需在任何循环中附加click处理程序。

Use a global variable as counter for the array index and increment it whenever you click the button: 使用全局变量作为数组索引的计数器,并在单击按钮时对其进行递增:

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

Demo: 演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM