2011-12-23 72 views
-3

可能重複:
is there a way to force event to fire only once on given element (per element, not whole document) when using live()?.live禁用雙擊

這是我的代碼:

$('.answerx').live('click', function(){ 
    comprobar($(this).attr('name') , "\'" + $(this).attr('id') + "\'"); 
}) 

我想讓它這樣一旦點擊已用戶無法再次點擊並運行該功能,因爲多次運行的功能正在讓我的程序變得瘋狂。

那麼,有沒有辦法讓這個點擊一次它禁用特定元素ID爲$(this).attr('id')

回答

3

你可以點擊標記對象作爲這樣就進一步點擊次數。有很多方法可以做到這一點。例如,添加一個類。

$('.answerx').live('click', function(){ 
    if(!$(this).hasClass('disabled')) { 
    comprobar($(this).attr('name') , "\'" + $(this).attr('id') + "\'"); 
    $(this).addClass('disabled'); 
    } 
}) 

添加一個類的其他好處是你可以分別設置被禁用的元素的樣式。

+0

所以不管我有多少元素與.answerx,這將只適用於一個已被點擊? – Jake 2011-12-23 21:30:00

+0

這是正確的。 – 2011-12-23 21:32:55

+0

如果你覺得這個答案有幫助,你應該接受它:-) – 2011-12-29 22:12:54

1

保持簡單:

var boolHasBeenRun = false; 
$('.answerx').live('click', function(){ 
    if(boolHasBeenRun === false){ 
     comprobar($(this).attr('name') , "\'" + $(this).attr('id') + "\'"); 
     boolHasBeenRun = true; 
    } 

}); 

或者

$('.answerx').live('click', function(){ 
     comprobar($(this).attr('name') , "\'" + $(this).attr('id') + "\'"); 
     $('.answerx').die('click');   

}); 

或者使用現代.off()

+1

'unbind'在這裏不起作用。它只解綁綁定了bind的事件處理函數。 – 2011-12-23 21:09:09

+0

謝謝,更新。 – 2011-12-23 21:11:47

+0

「die」的問題在於它除去了所有元素的事件處理程序,而不僅僅是單擊的元素。 – 2011-12-23 21:12:38