2013-03-25 67 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);