2014-12-26 25 views
0

所以我需要一個按鈕,以便它被點擊後禁用,然後在幾秒鐘後,它應該再次啓用。我添加了一個類按鈕禁用,因爲我想在同一頁面上使用它幾次。以下是我試過禁用然後在jquery中啓用按鈕

$(document).on('click', '.button-disabled', function(){ 
       $(this).prop('disabled', true); 
       setTimeout(function() { 
       $(this).prop('disabled', false); 
       }, 3500); 
       }); 


<button type="button" id="buttonSettings" class="btn btn-success button-disabled">Sacuvaj</button> 

我擡起頭,在網站上類似的問題,但沒有這些幫助,因爲每次按鈕並點擊後得到禁止,但它永遠不會被再次啓用。任何幫助,將不勝感激。

回答

7

setTimeout始終在全球範圍內被執行,因爲它是真的window.setTimeout(或者更準確地說WindowTimers),所以回調this內將是窗口,不是元素。

你要存儲的元素

$(document).on('click', '.button-disabled', function(){ 

     var element = $(this); 

     element.prop('disabled', true); 

     setTimeout(function() { 

      console.log(this); // gives "window" 

      element.prop('disabled', false); 

     }, 3500); 
}); 

一點題外話參考,新的瀏覽器接受額外的參數在setTimeout所以你也可以做

setTimeout(function(element) { 
    $(element).prop('disabled', false); 
}, 3500, this); 

或使用bind()

setTimeout(function() { 
    $(this).prop('disabled', false); 
}.bind(this), 3500); 
+0

謝謝先生,解決我的問題! – Chilipepper

+0

據我所知,你的最後一段是不正確的 - 儘管這樣可以將參數傳遞給回調函數,但這個函數不能通過傳遞來綁定。 –

+0

@FrédéricHamidi - 只是一個錯字,應該用這個參數來代替。 – adeneo

1

創建一個的實例&使用該實例刪除禁用。可以嘗試下面的東西。

$(document).on('click', '.button-disabled', function(){ 
 
    var self = $(this); 
 
    $(this).prop('disabled', true); 
 
    setTimeout(function() { 
 
     $(self).removeAttr('disabled'); 
 
    }, 3500); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<button type="button" id="buttonSettings" class="btn btn-success button-disabled">Sacuvaj</button>

+0

謝謝你的建議。 – Chilipepper