繁体   English   中英

禁用按钮,直到 function 完成

[英]Disable button until function is done

我正在尝试禁用该按钮,直到代码成功执行。 不幸的是,按钮激活得太早了,function 仍在运行。 我怎样才能防止这种情况?

$("#myButton").click(function() {
    $(this).prop("disabled", true)
    doSomethingFunction()
    $(this).prop("disabled", false)
});

编辑:谢谢大家的帮助。 我已经调整了我的代码。 你可以这样做还是有更好的方法?

class TestClass
{
    static doSomethingFunction() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () { console.log("function is done");  resolve(self);  }, 5000);
        })
    }
}

$("#myButton").click(function() {
    $(this).prop("disabled", true)
    TestClass.doSomethingFunction().then(r => $(this).prop("disabled", false))
});

第二种解决方案对我不起作用,因为在“功能完成”之前“完全完成”是 output

class TestClass
{
    static doSomethingFunction(callback) {
        setTimeout(function () { console.log("function is done");}, 2000);

        if(callback !== undefined){
            callback();
        }
    }
}

$("#myButton").click(function() {
    $(this).prop("disabled", true)

    TestClass.doSomethingFunction(function(){
        console.log("completely done")
    });
});

我究竟做错了什么?

考虑以下。

var myData;

function doSomethingFunction(callback){
  $.get("someplace.php", function(data){
    myData = data;
    if(callback !== undefined){
      callback();
    }
  });
}

$("#myButton").click(function() {
  var $self = $(this);
  $self.prop("disabled", true);
  doSomethingFunction(function(){
    console.log(myData);
    $self.prop("disabled", false);
  });
});

这允许您传入代码以在 function 完成后运行。 在此示例中,它可能正在从服务器获取数据。 这可能几乎不需要时间,或者生成报告可能需要 1.2 秒。 无论哪种方式,在 AJAX 成功之前它都不会运行。

也许使用 setTimeout() 添加一些延迟

https://www.w3schools.com/jsref/met_win_settimeout.asp

 $("#myButton").click(function() { $(this).prop("disabled", true) doSomethingFunction() setTimeout(function(){ $(this).prop("disabled", false) }, 500); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暂无
暂无

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

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