【问题标题】:Disabling buttons during API call在 API 调用期间禁用按钮
【发布时间】:2018-10-30 03:55:39
【问题描述】:

我试图在单击按钮时禁用该按钮,同时我运行一个调用 API 的函数,当它完成后我想重新启用该按钮。

我尝试了一些变体,例如attr()/removeAttr(),以及下面的$(this)$('#miss'),但奇怪的是当我只有禁用线按钮时禁用,当我禁用后跟启用时,例如在下面的代码中,按钮永远不会禁用。我错过了什么?

$('#miss').click(function() {
  $(this).prop('disabled', true);

  registerShot('miss');

  $(this).prop('disabled', false);
});

【问题讨论】:

  • 制作registerShot,不管它是什么,返回一个Promise,然后调用.thenawait,然后然后重新启用按钮。

标签: javascript jquery


【解决方案1】:

如果您的registerShot 函数编写没有问题,这将对您有所帮助:

$('#miss').click(function() {
  let missButton = $(this);
  $(missButton).prop('disabled', true);

  registerShot('miss')
    .then(function(res) {
      $(missButton).prop('disabled', false);
    });

});

【讨论】:

    【解决方案2】:

    问题是您的函数被异步调用,所以按钮 被禁用,但在调用 registerShot 后立即重新启用。

    您可以将元素传递给 registerShot,然后在函数末尾重新启用它:

    $('#miss').click(function () {
                $(this).prop('disabled', true);
                registerShot('miss',this);
            });
    
    function registerShot(p1,e) {
      //CodeHere
      (e).prop('disabled', false);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多