js中preventDefault 与stopPropagation 及 stopImmediatePropagation的区别

原文:https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

Three similar and often confused methods. Let’s explore the different between:

  • Event.preventDefault()
  • Event.stopPropagation()
  • Event.stopImmediatePropagation()

Summary

First off, let’s check out the MDN Summaries.

  • preventDefault: Cancels the event if it is cancelable, without stopping further propagation of the event.
  • stopPropagation: Prevents further propagation of the current event.
  • stopImmediatePropagation: Prevents other listeners of the same event from being called.

Event.preventDefault

Let’s look at a code example. We know that clicking the submit button on a form submits it to the form handler. Event.preventDefault is a perfect way to not submit a form when the submit button is clicked.

Event.preventDefault will ensure that the form is never submitted, but it won’t control or prevent that submit or click event from bubbling up. That’s what the other two are for.

Event.stopPropagation

stopPropagation ensures that the event doesn’t bubble any further. Let’s look at another code example:

Now if you were to click the link with the console open, you would see:

Now let’s add Event.stopPropagation:

And click the link again. This time we see:

Event.stopImmediatePropagation

This gets you 90% of everything you’ll need as far as manipulating events. But let’s pose a last use case that can prove difficult.

We’ll start off with similar markup, except we’ll give the anchor two classes. A generic one, item, that all anchors in this area will get, and a specific one, element, that’s very important for our application to work.

And we’ll add our nifty Event.stopPropagation we learned about in the last section!

But, when we click on the element we see:

The problem here is that item and element are evenly ranked in the DOM. It’s not as though it hits element and then bubbles up to container like we saw in the last example. Since the click event fires on both element and item at the same time, you cannot stopPropagation like you’d expect.

This is where stopImmediatePropagation comes in handy!

Now one important thing to note here is: Battles over immediate propagation go to the first one declared in your script ( or series of scripts ). So as you may have noticed, in order to get stopImmediatePropagation working we had to switch the listeners so that element comes before item!

Let’s run it one last time and we should see:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值