JQuery - 停止所有浏览器中的事件冒泡
我有一些大规模嵌套的 GUI 控件 - 当它们被单击或更改或任何我需要阻止事件在 DOM 树上进一步向上移动时。它需要在所有浏览器上运行。
此时我已经得到了一些相当笨重的 JS 代码:
//Do something in response to the original user action
//Leave it at that.
try {
e.stopPropagation();
}
catch (ex) {
}
try {
event.cancelBubble();
}
catch (ex) {
}
try {
event.preventDefault();
}
catch (ex) { }
...
这确实有效,但它闻起来和感觉起来都是错误的(我个人讨厌空的 catch 块)。我可以使用更简洁的 x 浏览器技巧吗?
I have some massively nested GUI controls - when they're clicked or changed or whatever I need to stop the event from going further up the DOM tree. It needs to work across all browsers.
At this point I've got some rather clunky JS code:
//Do something in response to the original user action
//Leave it at that.
try {
e.stopPropagation();
}
catch (ex) {
}
try {
event.cancelBubble();
}
catch (ex) {
}
try {
event.preventDefault();
}
catch (ex) { }
...
This does work, but it smells and feels wrong (personally I loathe empty catch blocks). Is there a neater x-browser trick I can use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 jQuery,则只需
event.stopPropagation()
即可工作美好的。 jQuery 统一了事件处理。一般来说,如果您想测试特殊的浏览器方法,您可以这样做:
这就是 jQuery 正在做的事情。它为事件创建包装器并提供统一的接口。
事件对象的名称由您定义。事件对象作为第一个参数传递给事件处理程序。您必须设置事件处理程序以接受参数,例如:
通常使用
e
或event
。If you use jQuery then just
event.stopPropagation()
will work fine. jQuery unifies the event handling.In general if, you want to test for special browser methods, you can do like so:
This is what jQuery is doing. It creates a wrapper for the event and provides a unified interface.
The name of the event object is defined by you. The event object is passed as first argument to your event handler. You have to setup the event handler to accept a parameter, e.g.:
Typically
e
orevent
are used.cancelBubble
是一个布尔属性,而不是Event
对象的方法。不需要 try/catch,因为您可以在使用之前测试所需的属性或方法。因此,如果没有 jQuery,以下代码将执行您想要的事件对象e
操作:cancelBubble
is a Boolean property rather than a method ofEvent
objects. There's no need for try/catch because you can test for the property or method you need before using it. So, without jQuery, the following will do what you want for an event objecte
: