Javascript:如何启用stopPropagation?
使用 object.stopPropagation()
我可以停止事件冒泡,但如何重新启用它?
js中有没有像object.startPropagation
这样的预定义函数?
编辑:
问题是,JS 会记住您是否单击“对象”,而不是始终停止事件冒泡,即使我不想要它,所以我想停止它:
document.getElementById("object").onclick = function(e){
if(e && e.stopPropagation) {
e.stopPropagation();
} else {
e = window.event;
e.cancelBubble = true;
}
}
With object.stopPropagation()
I can stop event bubbling but how can I re-enable it?
Is there a pre defined function in js something like object.startPropagation
?
EDIT:
The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:
document.getElementById("object").onclick = function(e){
if(e && e.stopPropagation) {
e.stopPropagation();
} else {
e = window.event;
e.cancelBubble = true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它根本不记得这个值。每次触发
onclick
时,e
事件都是新的。问题是你总是取消事件冒泡:e.stopPropagation
是W3C方法防止事件冒泡。
e.cancelBubble
是 Microsoft防止事件冒泡的方法。
他们都是一样的。所以你每次都会取消事件的冒泡。更多内容请阅读此处。
您需要更改方法,以便仅在满足您的条件时取消冒泡:
更新:
请记住,在当前代码中,如果浏览器支持
stopPropagation
,则if (e && e.stopPropagation)
将始终为 true。如果它进入cancelBubble 的第二个大括号,它将不会记住最后设置的值。请参阅这个小提琴。基本上,总而言之,在您的代码中,您每次点击后都会取消传播。您必须在函数中放入一些条件来确定是否取消元素层次结构中的传播。
It doesn't remember the value at all. The event
e
is new each timeonclick
is fired. The problem is you're always cancelling the event bubbling:e.stopPropagation
is the W3C methodof preventing event bubbling.
e.cancelBubble
is the Microsoftmethod to prevent event bubbling.
They're both the same. So you're cancelling bubbling of events every time. More reading here.
You'll need to change your method so that it only cancels bubbling if your criteria are met:
UPDATE:
Bear in mind that in your current code,
if (e && e.stopPropagation)
will always be true if the browser supportsstopPropagation
. If it goes into the second brace forcancelBubble
, it will not remember the value last set. See this fiddle.Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.