Javascript 防止在单击超链接时触发父容器单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1997084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent parent container click event from firing when hyperlink clicked
提问by Ben Foster
On my web page I have a list of files.
在我的网页上,我有一个文件列表。
Each file is in it's own container div (div class="file"). Inside the container is a link to the file and a description.
每个文件都在它自己的容器 div 中(div class="file")。容器内是文件的链接和说明。
I wanted to allow a user to click anywhere on the container to download the file. I did this by adding a click event to the container and retrieving the href of the child link.
我想让用户点击容器上的任何地方来下载文件。我通过向容器添加点击事件并检索子链接的 href 来做到这一点。
As the file opens in a new window, if the user actually clicks the link, the file opens twice.
当文件在新窗口中打开时,如果用户实际单击链接,文件将打开两次。
So I need to prevent the parent container click event from firing when the hyperlink is clicked. Would the best way of doing this be to add a click function to the hyperlink to0 and set event.stopPropagation? Presumably this would then stop the event from bubbling up to the container.
所以我需要防止父容器点击事件在点击超链接时触发。这样做的最佳方法是将点击功能添加到 to0 的超链接并设置 event.stopPropagation 吗?据推测,这将阻止事件冒泡到容器中。
Thanks Ben
谢谢本
采纳答案by pix0r
Yes, use stopPropagation. See: Prevent execution of parent event handler
是的,使用 stopPropagation。请参阅:防止执行父事件处理程序
回答by Luca Matteis
In the Microsoft model you must set the event's cancelBubble property to true.
在 Microsoft 模型中,您必须将事件的 cancelBubble 属性设置为 true。
window.event.cancelBubble = true;
In the W3C model you must call the event's stopPropagation() method.
在 W3C 模型中,您必须调用事件的 stopPropagation() 方法。
event.stopPropagation();
Here's a cross-browser solution if you're not using a framework:
如果您不使用框架,这是一个跨浏览器的解决方案:
function doSomething(e) {
if (!e) e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
回答by Ben Foster
Thanks for the help.
谢谢您的帮助。
I was using jQuery but it's good to know a non-framework solution.
我正在使用 jQuery,但很高兴知道非框架解决方案。
Added the following for the links:
为链接添加了以下内容:
$(".flink").click(function(e) {
e.stopPropagation();
});

