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

当前回答

你也可以试试这个

$("#clickable").click(function(event) {
    var senderElementName = event.target.tagName.toLowerCase();
    if(senderElementName === 'div') {
        // Do something here 
    } else {
        // Do something with <a> tag
    }
});

其他回答

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>

如果它在内联上下文中,在HTML中尝试这样做:

onclick="functionCall();event.stopPropagation();

下面是一个对我有用的非jQuery解决方案。

< div风格= "背景:青色;宽度:100 px;" onclick="if (event.srcElement==this) {console.log('outer');} <a style="background:red" onclick="console.log('inner');我“>点击< / > < / div >

对于那些没有使用jQuery

document.querySelector('.clickable').addEventListener('click', (e) =>{
    if(!e.target.classList.contains('clickable')) return
    // place code here
})

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

event.stopImmediatePropagation()

从这个解。