我目前使用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>

当前回答

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

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

其他回答

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

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

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

<a onclick="return false;" href="http://foo.example">I want to ignore my parent's onclick event.</a>

添加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;
   });

var inner = document.querySelector("#inner"); var outer = document.querySelector("#outer"); inner.addEventListener('click',innerFunction); outer.addEventListener('click',outerFunction); function innerFunction(event){ event.stopPropagation(); console.log("Inner Functiuon"); } function outerFunction(event){ console.log("Outer Functiuon"); } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Pramod Kharade-Event with Outer and Inner Progration</title> </head> <body> <div id="outer" style="width:100px;height:100px;background-color:green;"> <div id="inner" style="width:35px;height:35px;background-color:yellow;"></div> </div> </body> </html>

使用返回false;或e.stopPropogation ();将不允许执行其他代码。它会在这一点停止流动。