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

后端 未结 7 1285
余生分开走
余生分开走 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:22

    stopPropagation stops the event from bubbling up the event chain.

    preventDefault prevents the default action the browser makes on that event.

    Examples

    preventDefault

    $("#but").click(function (event) {
      event.preventDefault()
    })
    $("#foo").click(function () {
      alert("parent click event fired!")
    })
    
    

    stopPropagation

    $("#but").click(function (event) {
      event.stopPropagation()
    })
    $("#foo").click(function () {
      alert("parent click event fired!")
    })
    
    

    With stopPropagation, only the button's click handler is called while the div's click handler never fires.

    Where as if you use preventDefault, only the browser's default action is stopped but the div's click handler still fires.

    Below are some docs on the DOM event properties and methods from MDN:

    • event.cancelBubble
    • event.preventDefault()
    • event.returnValue
    • event.stopPropagation()

    For IE9 and FF you can just use preventDefault & stopPropagation.

    To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

提交回复
热议问题