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

当前回答

对于那些没有使用jQuery

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

其他回答

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

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

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

对于那些没有使用jQuery

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

如果单击子元素,则事件将弹出到父元素和事件。== event. currentarget。

所以在你的函数中,你可以检查这个并提前返回,即:

var url = $("#clickable a").attr("href");
$("#clickable").click(function(event) {
    if ( event.target !== event.currentTarget ){
        // user clicked on a child and we ignore that
        return;
    }
    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