jQuery: How do I use event.preventDefault() with custom events?

你说的曾经没有我的故事 提交于 2019-12-20 09:15:05

问题


How can I know in my triggering code that preventDefault has been called?

$(document).trigger('customEvent', params);
if (/* ??? */)
    doDefaultActions();

回答1:


trigger() can also take an event object, so if you can create an event object, like so:

var event = jQuery.Event("customEvent");
$(document).trigger(event);

then you can check after the trigger to see if preventDefault() has been called like so:

var prevented = event.isDefaultPrevented();



回答2:


If you're asking how to find out whether or not the default has been prevented, use:

event.isDefaultPrevented()

This will return 'true' or 'false' based on whether or not preventDefault() was called.

EDIT: http://api.jquery.com/event.isDefaultPrevented/




回答3:


Custom events do not have some default actions that happens .. (they are custom).

On the other hand, if you want to stop the bubbling effect of this event to others then have a look at triggerHandler which does not bubbles up to the hierarchy ..




回答4:


To my knowledge the "preventDefault()" call is about preventing the native browser responses to things like clicks on anchor tags or keypresses in text fields. Once the event handling cycle is over, it's over. For made-up events, I don't think it has any effect at all since it's all about the jQuery event processing system and not about native browser functionality.

Your code could set some sort of flag somewhere in order to communicate with the "outside world."

[edit] ooh you could try having the handler stash a reference to the event object somewhere that the exteral code can find it, and then externally check with "isDefaultPrevented()". I don't know whether that'd work however.




回答5:


In case someone needs it, as I did. Important the 2nd constructor-parameter:

Pure JS:

var event = new CustomEvent("close", { "cancelable": true });
// now event listeners can prevent default behavior
element.onclose(event);
// or: element.dispatchEvent(event);

if (!event.defaultPrevented)
    defaultBehavior();


来源:https://stackoverflow.com/questions/2229647/jquery-how-do-i-use-event-preventdefault-with-custom-events

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