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

当前回答

下面是一个使用Angular 2+的例子

例如,如果你想关闭一个模态组件,如果用户在它外面点击:

// Close the modal if the document is clicked.

@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
  this.closeModal();
}

// Don't close the modal if the modal itself is clicked.

@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
  event.stopPropagation();
}

其他回答

对于那些没有使用jQuery

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

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

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

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

如果有人在使用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创建一个模态效果。

如果单击子元素,则事件将弹出到父元素和事件。== 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;
})

使用stopPropagation方法,见示例:

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

正如jQuery文档所说:

stopPropagation方法防止事件在DOM中冒泡 树,防止任何父处理程序被通知该事件。

请记住,它不会阻止其他侦听器处理此事件(例如。),如果不是想要的效果,你必须使用stopImmediatePropagation代替。