有人可以解释一下这个 stopPropagation 是如何工作的吗?
我试图使用我在 Stackoverflow 上找到的一些代码来设置这种“当您单击元素外部时,关闭它”类型的东西:
$(document).click(function() {
$('.list-to-hide').hide();
});
$('.show-list-button').click(function(event) {
event.stopPropagation();
});
有人可以用 stopPropagation 解释后面的部分吗?我不明白为什么需要它。
谢谢! 马特
I was trying to setup this "when you click outside of the element, close it" type of thing using some code I found on Stackoverflow:
$(document).click(function() {
$('.list-to-hide').hide();
});
$('.show-list-button').click(function(event) {
event.stopPropagation();
});
Could someone explain the later part with stopPropagation? I don't understand why it's needed.
Thanks!
Matt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
想象一下:
和:
查看单击每个时会发生什么
当您单击跨度时,它也会发生触发 div 因为您还点击了 div。
现在,如果我们想要仅提醒跨度,我们需要在单击跨度时停止触发 div 单击,因此我们这样做:
看看现在会发生什么
Imagine this:
and:
Check out what happens when you click each one
When you click the span, it happens to also trigger the div because your also clicking the div.
Now if we wanted to alert the span only we need to stop the div click from triggering when we click on the span so we do this:
See what happens now
您的示例代码缺少一个重要部分:
如果没有
event.stopPropagation()
,它将显示列表,然后隐藏它,因为.show-list-button
是内部$(document)
以便两个点击处理程序都会触发。event.stopPropagation()
基本上表示仅将此点击事件应用于此子节点,并且不告诉父容器任何内容,因为我不希望它们这样做反应。。试想一下——你花 100 美元租一辆出租车。司机给了他的公司 80 美元。
event.stopPropagation()
就像告诉他保留所有 100 美元,因为公司不需要了解有关行程的任何信息。Your example code is missing a vital part:
Without the
event.stopPropagation()
, it would show the list, and then hide it because the.show-list-button
is inside the$(document)
so both click handlers would fire.event.stopPropagation()
basically says only apply this click event to THIS CHILD NODE and don't tell the parent containers anything because I don't want them to react.Think about it this way - you rent a taxi for $100. The driver gives his company $80.
event.stopPropagation()
is like telling him to keep all $100 because the company doesn't need to know anything about the ride.event.stopPropagation();
防止事件在 DOM 中冒泡。如果没有此行,单击.show-list-button
文档的单击处理程序也会触发。有了它,文档单击将不会触发。event.stopPropagation();
prevents the event from bubbling up the DOM. Without this line, clicking on.show-list-button
the click handler for document will fire also. With it, the document click will not fire.你读过这篇文章吗?
http://api.jquery.com/event.stopPropagation/
它防止事件冒泡DOM 树上,防止任何父处理程序收到该事件的通知。
示例
消除点击事件上的冒泡。
Have you read this ?
http://api.jquery.com/event.stopPropagation/
It prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Example
Kill the bubbling on the click event.