2013-03-25 108 views
0

我有一個腳本,在點擊按鈕後禁用按鈕,等待5秒鐘,然後再次啓用它。setTimeout無法正常工作

$(document).on('click', 'button', function() { 
    var htmls = $(this).html(); 
    $(this).prop("disabled", true); 
    setTimeout(function() { 
     $(this).prop("disabled", false); 
     $(this).html(htmls); 
    }, 5000); 
    $(this).html('<img src="<?=CDN('/icons/loading/loading5.gif ')?>" />'); 
}); 

不知何故setTimeout將不會結束,所以該按鈕將不會再次啓用。我沒有收到任何錯誤消息。

+1

超時結束,但'this'不引用DOM元素。詳細瞭解'this':https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this。 – 2013-03-25 10:39:53

回答

4

保存$(this)到變量之前setTimeout通話,因爲裏面setTimeout處理this關鍵字是指window對象:

$(document).on("click", "button", function() { 
    var $this = $(this), 
     htmls = $this.html(); 

    $this.prop("disabled", true) 
     .html('<img src="..." />'); 

    setTimeout(function() { 
     $this.prop("disabled", false) 
      .html(htmls); 
    }, 5000); 
}); 
+0

就是這樣,謝謝。 – 2013-03-25 10:41:50

2

這裏不指DOM element.Try投入另一個temarory variable.Because它setTimeOut

var $this = $(this), 
     htmls = $this.html(); 

    $this.prop("disabled", true); 
    setTimeout(function() { 
     $this.prop("disabled", false).html(htmls); 
    }, 5000);