How do I prevent a parent's onclick event from firing when a child anchor is clicked?

后端 未结 22 1756
旧巷少年郎
旧巷少年郎 2020-11-22 00:37

I\'m currently using jQuery to make a div clickable and in this div I also have anchors. The problem I\'m running into is that when I click on an anchor both click events ar

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:10

    In case someone had this issue using React, this is how I solved it.

    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; }
    

    Component's render():

    render() {
        ...
        return (
            
    {e.preventDefault();e.stopPropagation()}}> ... [modal content] ...
    ) }

    By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.

    This did the trick for me and I was able to create a modal effect with 2 simple divs.

提交回复
热议问题