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

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

问题描述

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

这是损坏的代码:

JavaScript

var url = $("#clickable a").attr("href");$("#clickable").click(function() {window.location = url;返回真;})

HTML

<!-- 其他内容.--><a href="http://foo.com">我不希望 #clickable 处理这个点击事件.</a>

解决方案

事件冒泡到 DOM 中已附加单击事件的最高点.因此,在您的示例中,即使 div 中没有任何其他明确可点击的元素,div 的每个子元素也会将它们的点击事件冒泡到 DOM 上,直到 DIV 的点击事件处理程序捕获它.

对此有两种解决方案,即检查事件的真正发起者.jQuery 将 eventargs 对象与事件一起传递:

$("#clickable").click(function(e) {var senderElement = e.target;//检查发件人是否为 

元素例如//if($(e.target).is("div")) {window.location = url;返回真;});

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

$("#clickable a").click(function(e) {//做点什么e.stopPropagation();});

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?

Here's the broken code:

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>

解决方案

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.

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天全站免登陆