jQuery:如何将 event.preventDefault() 与自定义事件一起使用?
我如何知道我的触发代码中已调用 preventDefault
?
$(document).trigger('customEvent', params);
if (/* ??? */)
doDefaultActions();
How can I know in my triggering code that preventDefault
has been called?
$(document).trigger('customEvent', params);
if (/* ??? */)
doDefaultActions();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
trigger() 也可以接受事件对象,因此如果您可以创建一个事件对象,如下所示:
那么您可以在触发器后检查以查看是否已调用 PreventDefault(),如下所示:
trigger() can also take an event object, so if you can create an event object, like so:
then you can check after the trigger to see if preventDefault() has been called like so:
万一有人需要它,就像我一样。重要的是第二个构造函数参数:
纯 JS:
In case someone needs it, as I did. Important the 2nd constructor-parameter:
Pure JS:
如果您询问如何查明默认是否已被阻止,请使用:
event.isDefaultPrevented()
这将根据是否阻止Default() 返回“true”或“false”被称为。
编辑:
http://api.jquery.com/event.isDefaultPrevented/
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/
自定义事件没有发生一些默认操作..(它们是自定义的)。
另一方面,如果您想停止此事件对其他人的冒泡影响,请查看
triggerHandler
不会冒泡到层次结构..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 ..据我所知,“preventDefault()”调用是为了防止本机浏览器响应诸如点击锚标记或文本字段中的按键之类的事情。一旦事件处理周期结束,一切就结束了。对于虚构的事件,我认为它根本没有任何效果,因为它完全与 jQuery 事件处理系统有关,而不与本机浏览器功能有关。
您的代码可以在某处设置某种标志,以便与“外部世界”进行通信。
[编辑]哦,您可以尝试让处理程序将对事件对象的引用存储在外部代码可以找到的地方,然后使用“isDefaultPrevented()”进行外部检查。我不知道这是否有效。
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.