How to prevent other event handlers, from first handler, in jQuery

浪尽此生 提交于 2019-12-17 16:31:44

问题


If you attach two or more event handlers to an HTML element, they would be executed one after the other. However, if you want to stop the subsequent event handlers, based on a condition checked in the first handler, then what you should do?

For example:

<div id='target'>
</div>

<p id='result'>
</p>

I'd like to cancel the second handler, if the first handler is cancelled.

$(function() {
    var target = $('#target'),
        result = $('#result');
    target.click(function(e) {
        result.append('first handler<br />');
        // Here I want to cancel all subsequent event handlers
    });
    target.click(function(e) {
        result.append('second handler<br />');
    });
});

You can see the fiddle here.

PS: I know that e.preventDefault() prevents the default action of the HTML element (for example, preventing an HTTP GET request being sent because of the click on a link), and e.preventPropagation() causes the event from being propagated to its parent elements in the DOM tree. I also know that it's possible to use a middle variable, set it to true in first handler, and check it in subsequent handlers. But I want to see if there is a more neat, sophisticated solution to this problem or not.


回答1:


See event.stopImmediatePropagation() - http://api.jquery.com/event.stopImmediatePropagation/

According to the jQuery API docs, this method:

Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.




回答2:


The solution is browser specific. See dojo.stopEvent:

dojo.stopEvent = function(/*Event*/ evt){
    // summary:
    //        prevents propagation and clobbers the default action of the
    //        passed event
    // evt: Event
    //        The event object. If omitted, window.event is used on IE.
    if(has("dom-addeventlistener") || (evt && evt.preventDefault)){
        evt.preventDefault();
        evt.stopPropagation();
    }else{
        evt = evt || window.event;
        evt.cancelBubble = true;
        on._preventDefault.call(evt);
    }
};

Updated fiddle: http://jsfiddle.net/pFp7P/1/



来源:https://stackoverflow.com/questions/8118489/how-to-prevent-other-event-handlers-from-first-handler-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!