用于循环onclick按钮 [英] For loop onclick button

查看:153
本文介绍了用于循环onclick按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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 ...?

推荐答案

正如其他人所说的,您不需要循环。您需要跟踪点击按钮的次数。

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.

解决这种不确定性的一种简单方法是使用 Promise s。他们将允许您只写一次逻辑,而不关心响应是否已到达。

A clean way to resolve this uncertainty is to use Promises. They will allow you to write the logic just once and not concern yourself with whether the response has arrived yet or not.

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>

这篇关于用于循环onclick按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆