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

后端 未结 22 1932
旧巷少年郎
旧巷少年郎 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:04

    Here's an example using Angular 2+

    For example, if you wanted to close a Modal Component if the user clicks outside of it:

    // 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();
    }
    

提交回复
热议问题