Cancel jQuery event handling

ⅰ亾dé卋堺 提交于 2019-12-04 19:29:08

问题


I have setup onclick event handler in the following manner:

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

Imagine there are event handlers setup using jQuery method bind() or similar handlers.

$('element').bind('click', function(){/*another function*/})

How can I prevent invoking handler defined with jQuery from the handler I have described in the beginning?

NB stopPropagation() and etc. jQuery's methods doesn't work from that function, because it is passed with native event object.


回答1:


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...




回答2:


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.




回答3:


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

return false;



回答4:


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.



来源:https://stackoverflow.com/questions/491707/cancel-jquery-event-handling

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