How to temporarily disable a click handler in jQuery?

前端 未结 12 2020
不思量自难忘°
不思量自难忘° 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:44

    You can do it like the other people before me told you using a look:

    A.) Use .data of the button element to share a look variable (or a just global variable)

    if ($('#buttonId').data('locked') == 1)
        return
    $('#buttonId').data('locked') = 1;
    // Do your thing
    $('#buttonId').data('locked') = 0;
    

    B.) Disable mouse signals

    $("#buttonId").css("pointer-events", "none");
    // Do your thing
    $("#buttonId").css("pointer-events", "auto");
    

    C.) If it is a HTML button you can disable it (input [type=submit] or button)

    $("#buttonId").attr("disabled", "true");
    // Do your thing
    $("#buttonId").attr("disabled", "false");
    

    But watch out for other threads! I failed many times because my animation (fading in or out) took one second. E.g. fadeIn/fadeOut supports a callback function as second parameter. If there is no other way just do it using setTimeout(callback, delay).

    Greets, Thomas

提交回复
热议问题