Best way to remove an event handler in jQuery?

前端 未结 20 2187
庸人自扰
庸人自扰 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:44

    You may be adding the onclick handler as inline markup:

    <input id="addreport" type="button" value="Add New Report" onclick="openAdd()" />
    

    If so, the jquery .off() or .unbind() won't work. You need to add the original event handler in jquery as well:

    $("#addreport").on("click", "", function (e) {
       openAdd();
    });
    

    Then the jquery has a reference to the event handler and can remove it:

    $("#addreport").off("click")
    

    VoidKing mentions this a little more obliquely in a comment above.

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

    This can be done by using the unbind function.

    $('#myimage').unbind('click');
    

    You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.

    There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs.

    Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.

    How to read bound hover callback functions in jquery

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

    I had to set the event to null using the prop and the attr. I couldn't do it with one or the other. I also could not get .unbind to work. I am working on a TD element.

    .prop("onclick", null).attr("onclick", null)
    
    0 讨论(0)
  • 2020-11-21 11:51

    Best way to remove inline onclick event is $(element).prop('onclick', null);

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

    Just Simply remove that from button:

    $('.classname').click(function(){
    $( ".classname" ).remove();
    });
    
    0 讨论(0)
  • 2020-11-21 11:55

    In case .on() method was previously used with particular selector, like in the following example:

    $('body').on('click', '.dynamicTarget', function () {
        // Code goes here
    });
    

    Both unbind() and .off() methods are not going to work.

    However, .undelegate() method could be used to completely remove handler from the event for all elements which match the current selector:

    $("body").undelegate(".dynamicTarget", "click")
    
    0 讨论(0)
提交回复
热议问题