2010-09-06 71 views

回答

9

禁用該按鈕,然後使用setTimeout運行幾秒鐘後啓用該按鈕的功能。

$('#some-button').attr("disabled", "disabled"); 
setTimeout('enableButton()', 5000); 

function enableButton(){ 
    $('#some-button').removeAttr('disabled'); 
} 
+0

工作的例子這不起作用:http://jsfiddle.net/RPQmM/相信的setTimeout叫錯了。 – Ender 2010-09-06 09:12:22

+2

@Ender它不起作用,因爲你的'enableButton'函數不在全局範圍內,這是*方法所要求的* setTimeout被調用。看到這個:http://jsfiddle.net/RPQmM/1/ – 2010-09-06 10:21:35

9

因爲這很可能是你可能會喜歡重複一個任務,我認爲要做到這一點的最好辦法是延長的jQuery像這樣:

$.fn.timedDisable = function(time) { 
    if (time == null) { time = 5000; } 
    return $(this).each(function() { 
     $(this).attr('disabled', 'disabled'); 
     var disabledElem = $(this); 
     setTimeout(function() { 
      disabledElem.removeAttr('disabled'); 
     }, time); 
    }); 
}; 

這將允許你打電話一組匹配元素上的一個函數,它將暫時禁用它們。按照寫法,您可以簡單地調用該函數,並且所選元素將被禁用5秒。你會做到這一點,像這樣:

$('#some-button').timedDisable(); 

您可以通過以下行改變5000調整默認時間設置:

if (time == null) { time = 5000; } 

您可以選擇在一個時間值傳遞以毫秒爲單位來控制長的元素將被禁用。例如:

$('#some-button').timedDisable(1000); 

這裏的工作演示:http://jsfiddle.net/fG2ES/

1

可能不是最完美的解決方案,但我想我會用這一個jQuery的隊列玩...

​$.fn.disableFor = function (time) { 
    var el = this, qname = 'disqueue'; 
    el.queue(qname, function() { 
     el.attr('disabled', 'disabled'); 
     setTimeout(function() { 
      el.dequeue(qname); 
     }, time || 3000); 
    }) 
    .queue(qname, function() { 
     el.removeAttr('disabled'); 
    }) 
    .dequeue(qname); 
}; 

$('#btn').click(function() { 
    ​$(this).disableFor(2000);​​​​ 
}); 

這是我的工作了...... http://jsfiddle.net/T9QJM/

而且,僅供參考,How do I chain or queue custom functions using JQuery?

2

試試這個。

(function(){ 
$('button').on('click',function(){ 
var $this=$(this); 
     $this 
      .attr('disabled','disabled'); 
      setTimeout(function() { 
      $this.removeAttr('disabled'); 
      }, 3000); 
     }); 
})(); 

您可以在這裏找到http://jsfiddle.net/informativejavascript/AMqb5/