2013-11-25 102 views
1

我使用的代碼from this post和雙擊預防工作,但是仍然按鈕並不preventDefault雙擊防止但防止默認不起作用

迴應任何人都可以伸出援助之手,請。

JS:

var myBtn = $('.myLink'); 
var handler = function(e){ 
    e.preventDefault(); 
    console.log("prevent 2x click"); 
    $(this).unbind('click'); 
    setTimeout(function(){ myBtn.click(handler); }, 500); 
} 
myBtn.click(handler); 

HTML:
<a class='myLink' href="#">my link to click</a>

+1

你沒有做任何事情來阻止傳播。 –

+1

你需要做'e.stopPropagation();' – PSL

+1

'e.preventDefault();'處理程序裏面呢? –

回答

1

原因是,當你解除綁定處理程序(其中有的preventDefault),並在時間的小週期多一個點擊進來它不」防止默認行爲。所以你可以附加一個專門的處理程序來防止默認並解除綁定你的其他邏輯的處理程序。試試這個方法:

var myBtn = $('.myLink'); 

var handler = function(e){ 
    $(this).unbind('click', handler); //unbind only your handler 
    setTimeout(function(){ 
      myBtn.click(handler); } 
    , 500); 
} 

myBtn.click(preventDefault); //have this bound to the anchor to prevent the default behavior always 

myBtn.click(handler); 

function preventDefault(e){ 
    e.preventDefault(); 
} 

Demo