Pros and Cons of using e.stopPropagation() to prevent event bubbling

前端 未结 3 1013
忘掉有多难
忘掉有多难 2021-02-03 13:43

Many people have explained that e.stopPropagation() prevents event bubbling. However, I\'m having a hard time finding why one would want or want to

3条回答
  •  天涯浪人
    2021-02-03 14:46

    Imagine you have a button and want to handle a click event:

    
    

    Without event propagation, clicking on the image or the text wouldn't trigger the click event handler bound to the button, as the event would never leave the or the elements.


    A case where you don't want event propagation is where nested elements have their own event handlers. Here's one example:

    
    

    If you don't stop the event propagation with .arrow's event handler, it will trigger the button's event handler as well.

提交回复
热议问题