Cancel jQuery event handling

后端 未结 4 1679
萌比男神i
萌比男神i 2021-02-14 12:36

I have setup onclick event handler in the following manner:

element.onclick = function() { /*code */ }

Imagine there are event handlers setup u

相关标签:
4条回答
  • 2021-02-14 13:14

    Jquery has a method for namespacing events. http://docs.jquery.com/Namespaced_Events

    You can add, trigger and remove separate functions bound to the same event via namespaces:

    $("a").bind("click.custom1",function(){ ... });
    $("a").bind("click.custom2",function(){ ... });
    $("a").trigger("click.custom2");
    $("a").unbind("click.custom2");
    

    As long as you unbind the namespaced event your normal onclick should be unaffected. You may have to bind two separate namespaces to the click event as above if that doesn't work.

    0 讨论(0)
  • 2021-02-14 13:15

    I'm not 100% sure what you're asking but maybe this will help:

    You can create a new event object (compliant with W3C DOM) via jQuery's exposed Event constructor:

    For example:

    element.onclick = function(e) {
        var aBetterEventObject = jQuery.Event(e);
        // Now you can do what you want: (Cross-browser)
        aBetterEventObject.preventDefault()
        aBetterEventObject.isDefaultPrevented()
        aBetterEventObject.stopPropagation()
        aBetterEventObject.isPropagationStopped()
        aBetterEventObject.stopImmediatePropagation()
        aBetterEventObject.isImmediatePropagationStopped()
    }
    

    EDIT: Reading through your question again, I don't think propagation is the problem - you seem to want to cancel an event handler from running within an event handler - I'm not sure this is possible. You could just unbind all handlers (jQuery(elem).unbind('click')) but I don't think that's what you're after...

    0 讨论(0)
  • 2021-02-14 13:21

    Following on from JimmyP's answer. I've tried this

    $('#x').click( function(e){
        alert('hello');
    });
    document.getElementById('x').onclick = function(){
        $('#x').unbind('click');
        alert("goodbye");
    }
    

    The jQuery event runs once in this example. I don't think you can rely on the order of handlers being invoked however you define them, so I guess you'll have to accept that the jQuery event might fire once. Adding the onclick first does prevent the jQuery event from firing at all but, as I said, I don't think that's reliable.

    0 讨论(0)
  • 2021-02-14 13:21

    try to add the following line in the jQuery event handler:

    return false;
    
    0 讨论(0)
提交回复
热议问题