Javascript: Disable the click event for 1 second after an ID is clicked

£可爱£侵袭症+ 提交于 2019-12-23 05:49:07

问题


Title pretty much describes my problem. I just need to disable the click event for precisely one second, so that I couldn't click on any other buttons on the webpage for that small duration. After the time gets over, I could click anywhere again.

Disabling other buttons for that one second is also acceptable.


回答1:


Try like,

$('#id').on('click',function(){
    // let a common class(disable-btn) for each button which should be disabled for on second
    $('.disable-btn').prop('disabled',true);
    setTimeout(function(){
       // enable click after 1 second
       $('.disable-btn').prop('disabled',false);
    },1000); // 1 second delay
});

$('#id').on('click', function() {
  // let a common class(disable-btn) for each button which should be disabled for on second
  $('.disable-btn').prop('disabled', true);
  setTimeout(function() {
    // enable click after 1 second
    $('.disable-btn').prop('disabled', false);
  }, 1000); // 1 second delay
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="id">Click to disable other for 1 second</button>
<br/>
<button class="disable-btn">Will Disable for 1 sec</button>
<br/>
<button class="disable-btn">Will Disable for 1 sec</button>
<br/>
<button>Will not Disable</button>
<br/>
<button class="disable-btn">Will Disable for 1 sec</button>
<br/>

You can disable the #id button itself by adding a class="disable-btn"




回答2:


    <!DOCTYPE html>
    <html>
    <body>

    <p>A script on this page starts this clock:</p>

    <p id="demo"></p>

    <script>

    function disableBtns() {
    document.getElementById("btn1").disabled = true; 
    document.getElementById("btn2").disabled = true; 
    var timer = setInterval(function(){enableBtns()},1000);
    //1000 means 1000 milliseconds
    }

    function enableBtns(){
    document.getElementById("btn1").disabled = false; 
    document.getElementById("btn2").disabled = false; 
    clearInterval(timer); 
    }
    </script>

    </body>

    <button id ="btn1" type="button" onclick="disableBtns()" >Button                            1</button>
    <button id ="btn2" type="button" onclick="disableBtns()" >Button                 2</button>
    </html>


来源:https://stackoverflow.com/questions/32002366/javascript-disable-the-click-event-for-1-second-after-an-id-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!