What's the difference between event.stopPropagation and event.preventDefault?

后端 未结 7 1284
余生分开走
余生分开走 2020-11-22 00:52

They seem to be doing the same thing...
Is one modern and one old? Or are they supported by different browsers?

When I handle events myself (without framework) I

7条回答
  •  鱼传尺愫
    2020-11-22 01:38

    Event.preventDefault- stops browser default behaviour. Now comes what is browser default behaviour. Assume you have a anchor tag and it has got a href attribute and this anchor tag is nested inside a div tag which has got a click event. Default behaviour of anchor tag is when clicked on the anchor tag it should navigate, but what event.preventDefault does is it stops the navigation in this case. But it never stops the bubbling of event or escalation of event i.e

    
    
    $('.container').on('click', function(e) {
     console.log('container was clicked');
    });
    
    $('.element').on('click', function(e) {
      e.preventDefault(); // Now link won't go anywhere
      console.log('element was clicked');
    });
    

    The result will be

    "element was clicked"

    "container was clicked"

    Now event.StopPropation it stops bubbling of event or escalation of event. Now with above example

    $('.container').on('click', function(e) {
      console.log('container was clicked');
    });
    
    $('.element').on('click', function(e) {
      e.preventDefault(); // Now link won't go anywhere
      e.stopPropagation(); // Now the event won't bubble up
     console.log('element was clicked');
    });
    

    Result will be

    "element was clicked"

    For more info refer this link https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

提交回复
热议问题