Best way to remove an event handler in jQuery?

前端 未结 20 2317
庸人自扰
庸人自扰 2020-11-21 11:38

I have an input type=\"image\". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image

相关标签:
20条回答
  • 2020-11-21 11:39

    Updated for 2014

    Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing $( "#foo" ).off( ".myNamespace" );

    0 讨论(0)
  • 2020-11-21 11:40

    This wasn't available when this question was answered, but you can also use the live() method to enable/disable events.

    $('#myimage:not(.disabled)').live('click', myclickevent);
    
    $('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });
    

    What will happen with this code is that when you click #mydisablebutton, it will add the class disabled to the #myimage element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the .live() selector valid again.

    This has other benefits by adding styling based on that class as well.

    0 讨论(0)
  • 2020-11-21 11:40

    All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:

    $(document).on("click", ".button", function() {
        doSomething();
    });
    


    My workaround:

    As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:

    // prevent another click on the button by assigning another class
    $(".button").attr("class","buttonOff");
    

    Hope that helps.

    0 讨论(0)
  • 2020-11-21 11:41

    This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/

    $('#myimage').removeAttr("click");
    
    0 讨论(0)
  • 2020-11-21 11:42

    I know this comes in late, but why not use plain JS to remove the event?

    var myElement = document.getElementById("your_ID");
    myElement.onclick = null;
    

    or, if you use a named function as an event handler:

    function eh(event){...}
    var myElement = document.getElementById("your_ID");
    myElement.addEventListener("click",eh); // add event handler
    myElement.removeEventListener("click",eh); //remove it
    
    0 讨论(0)
  • 2020-11-21 11:44

    maybe the unbind method will work for you

    $("#myimage").unbind("click");
    
    0 讨论(0)
提交回复
热议问题