简体   繁体   English

For循环onclick按钮

[英]For loop onclick button

<button type="button" onclick="loadDoc()">Scimba text</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    for (var i = 1; i<5; i++){
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById(i).innerHTML = xhttp.responseText;
      }
    }
  };
  xhttp.open("GET", "info1.txt", true);
  xhttp.send();
}
</script>

Hello everybody ! 大家好 ! Need some help ... How can I make the for loop to iterate one time when I click the button and when the button is clicked for the second time the loop will iterate also the second time and so on ...? 需要一些帮助...当我单击按钮时,如何使for循环迭代一次,第二次单击按钮时,循环也会第二次迭代,依此类推...?

Forget about using a loop. 忘记使用循环了。 Loops are for when you want to immediately do something a number of times. 循环适用于您想要立即执行多次操作的情况。

At its core, this comes down to incrementing a value each time the click event happens and then do something based on what that new value is. 从本质上讲,这可以归结为每次单击事件发生时增加一个值,然后根据新值是什么来做一些事情。

Start by making i a variable outside the scope of the event handler function. 首先将i设为事件处理程序函数范围之外的变量。 The simple approach for this would be to make i a global. 一个简单的方法就是使i成为一个全球性的公司。

(The nicer approach would be to use an IIFE to scope i and assign the event handler function with JavaScript instead of HTML.). (更好的方法是使用IIFE来确定范围i使用JavaScript而不是HTML分配事件处理函数。)

Then, inside the event handler function: 然后,在事件处理函数中:

  1. increment i 增加i
  2. get the data you want 获取您想要的数据
  3. put the data in the appropriate place based on the value of i 根据i的值将数据放在适当的位置

You should use a counter. 您应该使用一个计数器。

Declare a global variable (with var) and increase it every time you loop. 声明一个全局变量(使用var),并在每次循环时增加它。

As Quentin said since you want to manually increment your loop, you no longer can use a for loop. 正如Quentin所说,由于您要手动递增循环,因此不再可以使用for循环。 You should do something like this http://jsfiddle.net/t97ou0ny/ . 您应该执行类似http://jsfiddle.net/t97ou0ny/的操作 This will increment count on every click, if greater than limit, resets count to 0. 这将使每次点击的计数增加,如果大于限制,则将计数重置为0。

HTML HTML

<body>
  <div id="count">0</div>
  <button id="inc-btn">
    Increment
  </button>
</body>

JS JS

$(document).ready(function() {
  var count = 0;
  var limit = 5;
  var count_div = $('#count');
  var increment_btn = $('#inc-btn');

  increment_btn.click(function() {
    if (++count > limit) {
      count = 0;
    }

    count_div.text(count);
  });
});

As others have said, you don't need a loop. 正如其他人所说,您不需要循环。 You need something to keep track of how many times the button has been clicked. 您需要一些东西来跟踪单击按钮的次数。

However, this is tricky because you don't know whether the user will click the button before or after the response has returned. 但是,这很棘手,因为您不知道用户是在响应返回之前还是之后单击按钮。 If they click the button before the response gets back, you need to loop when the response gets back to catch up to the number of button clicks that have already taken place. 如果他们在响应返回之前单击按钮,则需要在响应返回时循环以赶上已经发生的按钮单击次数。 If they click the button after the response returns, you have to hold on to the response and use it upon the user's click. 如果他们在响应返回后单击按钮,则必须保留响应并在用户单击时使用它。

A clean way to resolve this uncertainty is to use Promise s. 解决此不确定性的一种干净方法是使用Promise They will allow you to write the logic just once and not concern yourself with whether the response has arrived yet or not. 它们将使您仅编写逻辑一次,而不必担心响应是否已经到来。

plnkr example plnkr示例

<button type="button" onclick="loadDoc()">Scimba text</button>

<script>
window.loadDoc = (function () {
    var i = 1;
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "info1.txt", true);
    xhttp.send();

    // create a promise for the result
    var pResponse = new Promise(function (resolve) {
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                resolve(xhttp.responseText);
            }
        };
    });

    return function () {
        if (i < 5) {
            var c = i;
            // chain off the promise once for each click
            pResponse.then(function (response) {
                document.getElementById(c).innerHTML = response;
            });
            i += 1;
        }
    };
})();
</script>

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

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