2011-04-29 80 views
5

我希望點擊我的按鈕後,它會幾秒鐘無法點擊,我該怎麼做?我想爲所有按鈕編寫代碼,而不僅僅是一個。所以,我需要類似的東西:如何使按鈕點擊後不可點擊?

$(document).ready(function() {  
    $('input[type="button"]').click(function() { 
     $(this).css("hidden: true"); 
     delay(3); 
     $(this).css("hidden: normal"); 
    })  
}) 

這只是一個僞代碼,你能幫我一下嗎?

回答

10

使用jQuery ...

$(document).ready(function() {  
    $('input[type="button"]').click(function() { 
     var input = this; 
     input.disabled = true; 
     setTimeout(function() { 
      input.disabled = false; 
     }, 3000); 

    });  
}); 

jsFiddle

沒有jQuery的...

document.addEventListener('DOMContentLoaded',() => {  
    document.querySelectorAll('input[type="button"]') 
    .addEventListener('click', (e) => { 
     let input = e.target; 
     input.disabled = true; 
     setTimeout(function() { 
      input.disabled = false; 
     }, 3000); 

    });  
}); 

或者捕捉持久的祖先元素上的點擊次數和檢查,如果他們input[type="button"]類型。這可以防止爲每個元素附加多個事件。

+3

'this'將在匿名函數中具有錯誤的上下文,因此這將不起作用 – davin 2011-04-29 10:22:59

+2

@達文不知道爲什麼我忘了那個。我做了一個編輯:) – alex 2011-04-29 10:25:49

+0

完美的作品,謝謝。 – 2011-04-29 10:32:35

2

添加禁用的屬性。

$(this).attr('disabled', true); 
+0

這就是我一直在尋找,但它似乎並沒有被回答的問題。 ;)thx – Bachet 2011-09-29 14:27:46

4

禁用的元件是通過將disabled屬性,給它的值disabled完成。再次啓用它是通過刪除屬性來完成的。

更新:修復了使用setTimeout的答案 - 抱歉與$.delay混淆。

$(document).ready(function() {  
    $('input[type="button"]').click(function() { 
     var el = $(this); 
     el.attr('disabled', 'disabled'); 
     setTimeout(function() { el.removeAttr('disabled'); }, 3000); 
    })  
}) 
+1

延遲不會這樣工作:http://api.jquery.com/delay/ – ezmilhouse 2011-04-29 10:25:44

+1

這[對我來說不行](http://jsfiddle.net/5287e/)對我來說,我做了些什麼錯誤?我的印象是'delay()'只適用於效果隊列。 – alex 2011-04-29 10:26:45

+0

@alex - 沒錯,你需要使用setTimeout,見下面 – ezmilhouse 2011-04-29 10:29:22

0

這應該這樣做。

$(document).ready(function() {  
    $('input[type="button"]').click(function() { 
     $(this).hide().delay(3000).show(); 
    })  
}) 
0

小提琴這裏:http://jsfiddle.net/ezmilhouse/Hw6Gf/1/

$(document).ready(function() {  
    $('input[type="button"]').click(function() { 
     $(this).attr('disabled','disabled'); 
     setTimeout(function() { 
      $('input[type="button"]').removeAttr('disabled'); 
     }, 3000); 

    });  
});