disable click event handler for a duration of time

放肆的年华 提交于 2019-12-04 05:09:34

Another approach to the whole problem is not to bother with unbinding and rebinding and just use a "disabled" flag:

$(document).ready(function(){

   var clickDisabled = false;
   $('#click').click(function(){
      if (clickDisabled)
         return;

      // do your real click processing here

      clickDisabled = true;
      setTimeout(function(){clickDisabled = false;}, 2000);
  });

});

When you are rebinding the function the second time you are binding just a subset of all your code - all it does it output bound to the status, but it doesn't contain any of the code for doing a timeout a second time.

Also, you will like the .one() function.

I've fixed up your code here: http://jsfiddle.net/eQUne/6/

function bindClick() {
    $('#click').one('click', function() {
        $('#status').append("bound ");
        setTimeout(bindClick, 2000);
    });
}

$(document).ready(function(){
    bindClick();
});

Try this:

$(document).ready(function(){

$('#click').click(function(){

    $('#click').unbind('click');
    $('#status').append("unbound ");

    setTimeout(
        function(){
            $('#click').bind('click',function(){

            });
            $('#status').append("bound ");           
        },
        2000
        );
    });
});

You misspelled setTimeout and your "bound" message was being appended only on click.

If I got what you were asking correctly, this should work:

<div id="click" >time out</div>
<div id="status"></div>

$(document).ready(function() {
    $('#click').click(unbindme);

    $('#status').html('bound'); 

    function unbindme()
    {
        $('#click').unbind('click');
        $('#status').html('unbound');

        setTimeout(function(){
            alert('here');
            $('#status').html('bound'); 
            $('#click').click(unbindme);   
        }, 2000);
    }
}

Check it out here: http://jsfiddle.net/eQUne/

I answer your question but just don't kill yourself :)) Just kidding... Your code is fine just a typo: setTimeOut should be setTimeout (the O should be o)

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