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

当前回答

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

对此有两种解决方案,一是检查到底是谁发起了这个事件。jQuery将一个eventargs对象和事件一起传递:

$("#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;
});

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

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

其他回答

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>

你也可以试试这个

$("#clickable").click(function(event) {
    var senderElementName = event.target.tagName.toLowerCase();
    if(senderElementName === 'div') {
        // Do something here 
    } else {
        // Do something with <a> tag
    }
});
<a onclick="return false;" href="http://foo.example">I want to ignore my parent's onclick event.</a>

所有的解决方案是复杂的和jscript。下面是最简单的版本:

var IsChildWindow=false;

function ParentClick()
{
    if(IsChildWindow==true)
    {
        IsChildWindow==false;
        return;
    }
    //do ur work here   
}


function ChildClick()
{
    IsChildWindow=true;
    //Do ur work here    
}

e.s stoppropagation()是一个正确的解决方案,但如果你不想在你的内部锚上附加任何事件处理程序,你可以简单地将这个处理程序附加到你的外部div:

e => { e.target === e.currentTarget && window.location = URL; }