首页 > 解决方案 > HTML按钮文本在无限循环之前不会改变

问题描述

在下面的代码中:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<button type="button" class="btn btn-danger" id="TxChg">Proceed</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script>
  idcate = 0;

  function checkbuff() {
    while ((idcate == 0)) {
      mis = new Date().getSeconds() % 30;
      if (mis == 2) {
        idcate = 1;
      }
    }
  }
  $('#TxChg').click(function() {
    document.getElementById("TxChg").innerHTML = "<i class='fa fa-refresh fa-spin'></i>Processing...";
    checkbuff();
  });
</script>

我想让“Txchg”按钮在 checkbuff() 函数运行之前将其文本更改为“Processing...”。

我不知道为什么这段代码总是先运行 checkbuff() 函数然后我会看到按钮改变了它的文本?

标签: javascriptjqueryhtmlbootstrap-4

解决方案


由于您正在等待特定的一秒发生,而不是垃圾邮件循环您的系统,您应该在该秒执行您的逻辑循环。你也可以 setTimeout 你的初始调用,让浏览器有机会重绘。

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<button type="button" class="btn btn-danger" id="TxChg">Proceed</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script>
  idcate = 0;

  function checkbuff() {
    if (!idcate) {
      var mis = new Date().getSeconds() % 30;
      
      console.log(mis);
      
      if (mis === 2) {
        idcate = 1;
      } else {
        setTimeout(checkbuff, 1000);
      }
    }
  }
  
  $('#TxChg').click(function() {
    document.getElementById("TxChg").innerHTML = "<i class='fa fa-refresh fa-spin'></i>Processing...";
    setTimeout(checkbuff, 0);
  });
</script>


推荐阅读