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

当前回答

您可以检查目标是否不是div元素,然后在父元素上发出另一个单击事件,之后您将从句柄“返回”。

$('clickable').click(function (event) {
    let div = $(event.target);
    if (! div.is('div')) {
       div.parent().click();
       return;
    }
    // Then Implement your logic here
}

其他回答

如果你在可点击的div中有多个元素,你应该这样做:

$('#clickable *').click(function(e){ e.stopPropagation(); });

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

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

这就是你要找的

mousedown事件。这适用于每个DOM元素,以防止javascript的焦点处理程序,像这样:

$('.no-focus').mousedown(function (e) {
   e.prevenDefault()

   // do stuff
}

在vue.js框架中,你可以这样使用修饰符:

<span @mousedown.prevent> no focus </span>

注意,使用on输入将阻止文本选择处理程序

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

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

如果有人在使用React时遇到这个问题,这就是我解决它的方法。

scss:

#loginBackdrop {
position: absolute;
width: 100% !important;
height: 100% !important;
top:0px;
left:0px;
z-index: 9; }

#loginFrame {
width: $iFrameWidth;
height: $iFrameHeight;
background-color: $mainColor;
position: fixed;
z-index: 10;
top: 50%;
left: 50%;
margin-top: calc(-1 * #{$iFrameHeight} / 2);
margin-left: calc(-1 * #{$iFrameWidth} / 2);
border: solid 1px grey;
border-radius: 20px;
box-shadow: 0px 0px 90px #545454; }

组件的呈现():

render() {
    ...
    return (
        <div id='loginBackdrop' onClick={this.props.closeLogin}>
            <div id='loginFrame' onClick={(e)=>{e.preventDefault();e.stopPropagation()}}>
             ... [modal content] ...
            </div>
        </div>
    )
}

通过为子模式(content div)添加onClick函数,可以防止鼠标点击事件到达父元素的“closeLogin”函数。

这对我来说很有用,我可以用2个简单的div创建一个模态效果。