Prevent on click on parent when clicking button inside div

前端 未结 5 1845
悲哀的现实
悲哀的现实 2020-12-29 02:03

Is it possible to prevent the function on the

element from running when clicking the button inside the div?

When clicking the button element

5条回答
  •  执笔经年
    2020-12-29 02:36

    Here is how to master this problem.

    Say you have a parent element and some child elements.

    1.(1st case) You want the parent click to do not affect the child clicks. Just put at the parent element the .self modifier:

      
    Child1 Child2 Child3

    See it in action here

    note: if you remove the .self when you click a child, the parent event will fire too.

    2.(2nd case) You have the below code:

      
    Click to activate

    The problem is:

    1. When you click the icon element the parent click will fire. (you don't want this)
    2. You can NOT use the 1st solution because you want to fire the parent event even if the text "Click to activate" gets clicked.

    The solution to this is to put the .stop modifier to the icon element so the parent event will not fire.

    See it in action here

提交回复
热议问题