2014-01-31 60 views
0

我想,當用戶點擊一個按鈕如何在我的情況下禁用按鈕點擊事件?

HTML

<a href='#' id='btn' >click me</a> 

的js

$('#btn').on('click', function(){ 
      clearInterval(instance.timer); 
      var timer=setInterval(function(){Timer()},3000); 
    }) 

function Timer(){ 
    //do stuff…. 
    } 

我希望在3秒等待時間禁用按鈕單擊事件創建一個定時器。我該怎麼做呢?謝謝您的幫助!

+0

你需要某種你設定的時間間隔之前所觸發的事件,另一個被觸發之後的時間間隔。如果你把它放在同一個方法中,那麼在你離開這個方法之前,它將被禁用,定時器運行並啓用。所以當點擊您禁用,設置間隔,並啓動計時器。您需要在計時器過期時觸發另一個事件,以重新啓用該按鈕。 –

+0

@FlyingCat您想在頁面加載後禁用點擊三秒鐘,或者在初始點擊後禁用點擊三秒鐘? –

回答

1

使用本地JavaScript就可以輕鬆啓用按鈕,頁面加載3秒後:

document.getElementById("btn").onclick = function(e){ 
    e.preventDefault(); 
}; 

setTimeout(function(){ 
    document.getElementById("btn").onclick= function(){ 
     //add implementation 
    }; 
},3000); 

JS小提琴:http://jsfiddle.net/84f9S/

如果你只是想點擊後封鎖三秒按鈕您可以使用以下內容:

var enabled = true; 
$("#btn").click(function(){ 
    if(enabled){ 
     enabled = false; 
     alert("action"); 
     setTimeout(function(){ 
      enabled = true;   
     },3000); 
    } 
}); 

JS小提琴:http://jsfiddle.net/84f9S/1/

0

如果我誤解了你,對不起!

I was hoping to disable the button click event during the 3 second wait time 

這意味着對我來說,「用戶等待3秒,然後按鈕應該啓用」,對吧?

,如果是這樣的話,那麼使用setInterval(....)是不正確的,bacause,時間是指:「做一些事情,每3秒」

我會建議你做這樣的事情:

jQuery(document).ready(function($){ 
    $("#btn").click(function(){ 
      $(this).prop("disabled",true); 
      var btn = $(this); 
      setTimeout(function(){ 
         btn.prop("disabled",false); 
      },3000); 

    }); 
}); 

DEMO:http://jsfiddle.net/LZTuQ/1/

0

請參閱js小提琴示例。我知道你在你的問題中提到了一個計時器,但你可以通過添加禁用的attr on按鈕來簡化代碼,並且只有當複選框被選中時才啓用它。當前代碼僅在複選框被選中時激活按鈕。 http://jsfiddle.net/S9Sa5/

我做了一些調整,HTML

<div> 
    <input type="checkbox" id="TermsandConditions" name="TermsandConditions" /> 
    <label for="TermsandConditions" class='ff-label' style='display:inline; color:#990000'><strong>I have read and agree to the Terms of Use.</strong> 
    </label> 
    <br /> 
    <input type="button" id="submitbutton" name="submit" type="submit" value="Submit" disabled="true" /> 
</div> 

jQuery的:

$("input").on('click', function() { 
    $this = $(this); 
    var submitbutton = $("#submitbutton"); 
    if (!$this.is(":checked")) { 
     alert("Please check the agreement check box"); 
     submitbutton.attr('disabled', 'true'); 
    } else { 
     submitbutton.removeAttr('disabled'); 
    } 
}); 
相關問題