我正在嘗試禁用該按鈕,直到代碼成功執行。不幸的是,按鈕激活得太早,該功能仍在運行。我怎樣才能防止這種情況?
$("#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))
});
第二種解決方案對我不起作用,因為在“功能完成”之前輸出“完全完成”
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")
});
});
我究竟做錯了什么?
uj5u.com熱心網友回復:
考慮以下。
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);
});
});
這允許您傳入代碼以在函式完成后運行。在這個例子中,也許它正在從服務器獲取資料。這可能幾乎不需要時間,或者生成報告可能需要 1.2 秒。無論哪種方式,它都不會運行,直到 AJAX 成功。
uj5u.com熱心網友回復:
也許使用 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363229.html
標籤:javascript 查询
下一篇:useState不會呈現頁面
