简体   繁体   English

使用 onclick 事件中断并继续循环

[英]Break and continue for loop with onclick event

I have made a function in which I have tried to get multiple of nos by onclick event.我制作了一个 function ,其中我试图通过 onclick 事件获得多个 nos。 I want to get the multiples like onclick of button one time print multiple of 2 and then onclick on button second time print multiple of 3 and so on.我想获得像 onclick 这样的倍数,按钮一次打印 2 的倍数,然后 onclick 按钮第二次打印 3 的倍数,依此类推。

In my function I am getting all the multiples of nos which are less than 11. That means the entire loop is running on a single click.在我的 function 中,我得到了所有小于 11 的倍数。这意味着整个循环只需单击一下即可运行。

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>
<button onclick="myFunction()">Get Multiples of Int</button>
<p id="demo"></p>

<script>
function myFunction() {
var value = "";
var i, j;
for (i = 2; i < 11; i++) {

    for (j = 1; j < 11; j++) {

    value += "Multiples of " + i + " " + (i * j) + "<br>"; 
    }
}
document.getElementById("demo").innerHTML = value;
}
</script>

</body>
</html>

Try this,尝试这个,

 let clickCount = 1 function myFunction() { var value = ""; clickCount++; for (j = 1; j < 11; j++) { value += "Multiples of " + clickCount + " " + (clickCount * j) + "<br>"; } document.getElementById("demo").innerHTML = value; }
 <h2>JavaScript Arrays</h2> <button onclick="myFunction()">Get Multiples of Int</button> <p id="demo"></p>

Instead of using two loops you can use counter variable and increment on every click.您可以使用计数器变量并在每次点击时递增,而不是使用两个循环。

<body>

  <h2>JavaScript Arrays</h2>
  <button onclick="myFunction()">Get Multiples of Int</button>
  <p id="demo"></p>

  <script>
    var counter = 2;
    function myFunction() {
      var value = "";
      var i, j;
      for (j = 1; j < 11; j++) {

        value += "Multiples of " + counter + " " + (counter * j) + "<br>";
      }
      counter++;
      document.getElementById("demo").innerHTML+= value;
    }
  </script>

</body>

</html>

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

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