如何在单击子锚点时阻止父级的onclick事件触发? [英] How do I prevent a parent's onclick event from firing when a child anchor is clicked?

查看:140
本文介绍了如何在单击子锚点时阻止父级的onclick事件触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用jQuery使div可点击,在这个div我也有锚点。我遇到的问题是,当我点击一个锚点时,两个点击事件都会被触发(对于div和锚点)。如何在单击锚点时阻止div的onclick事件触发?

I'm currently using jQuery to make a div clickable and in this div I also have anchors. The problem I'm running into is that when I click on an anchor both click events are firing (for the div and the anchor). How do I prevent the div's onclick event from firing when an anchor is clicked?

这是损坏的代码:

JavaScript

var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
    window.location = url;
    return true;
})

HTML

<div id="clickable">
    <!-- Other content. -->
    <a href="http://foo.com">I don't want #clickable to handle this click event.</a>
</div>


推荐答案

事件泡到DOM中的最高点已附加点击事件。所以在你的例子中,即使div中没有​​任何其他明确可点击的元素,div的每个子元素都会将它们的click事件向上冒泡到DOM,直到DIV的click事件处理程序捕获它为止。

Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.

这有两个解决方案,即检查实际发起事件的人。 jQuery传递一个eventargs对象以及事件:

There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:

$("#clickable").click(function(e) {
    var senderElement = e.target;
    // Check if sender is the <div> element e.g.
    // if($(e.target).is("div")) {
    window.location = url;
    return true;
});

您还可以在链接上附加一个点击事件处理程序,告诉他们在自己的处理程序执行后停止事件冒泡

You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:

$("#clickable a").click(function(e) {
   // Do something
   e.stopPropagation();
});

这篇关于如何在单击子锚点时阻止父级的onclick事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆