How to temporarily disable a click handler in jQuery?

前端 未结 12 2022
不思量自难忘°
不思量自难忘° 2020-12-04 14:02

Say I have something like the following to trap the click event of a button:

$(\"#button_id\").click(function() {
  //disable click event
  //do something
           


        
12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 14:52

    If #button_id implies a standard HTML button (like a submit button) you can use the 'disabled' attribute to make the button inactive to the browser.

    $("#button_id").click(function() {
        $('#button_id').attr('disabled', 'true');
    
        //do something
    
         $('#button_id').removeAttr('disabled');
    });   
    

    What you may need to be careful with, however, is the order in which these things may happen. If you are using the jquery hide command, you may want to include the "$('#button_id').removeAttr('disabled');" as part of a call back, so that it does not happen until the hide is complete.

    [edit] example of function using a callback:

    $("#button_id").click(function() {
        $('#button_id').attr('disabled', 'true');
        $('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
    });   
    

提交回复
热议问题