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

下面是破碎的代码:

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.example">I don't want #clickable to handle this click event.</a>
</div>

当前回答

添加a如下:

<a href="http://foo.example" onclick="return false;">....</a>

或者返回false;从点击处理程序#clickable像:

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

其他回答

和ev比较。当这个不可用时(React等)。

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

如果在任何情况下都不打算与内部元素交互,那么CSS解决方案可能对您有用。

只需将内部元素/s设置为pointer-events: none

在你的情况下:

.clickable > a {
    pointer-events: none;
}

或笼统地针对所有内部元素:

.clickable * {
    pointer-events: none;
}

这个简单的hack在用ReactJS开发时为我节省了很多时间

浏览器支持可以在这里找到:http://caniuse.com/#feat=pointer-events

如果有人需要写信(为我工作过):

event.stopImmediatePropagation()

从这个解。

这里是我的解决方案,每个人都在寻找一个非jquery代码(纯javascript)

document.getElementById("clickable").addEventListener("click", function(e) {
    e = window.event || e; 
    if(this === e.target) {
      // put your code here
    }
});

如果点击父级的子级,你的代码将不会被执行

您需要阻止事件到达父节点(div)(冒泡)。 请参阅此处关于冒泡的部分,以及此处特定于jquery的API信息。