event.stopPropagation与event.preventDefault()与在DOM事件中返回false

I feel like I’m always confused by one thing when it comes to handling DOM events in JavaScript.

在处理JavaScript中的DOM事件时,我总是感到一头雾水。

When should I call stopPropagation() on the event object? When should I call preventDefault() on the event object? Should I return false?

什么时候应该在事件对象上调用stopPropagation() ? 什么时候应该在事件对象上调用preventDefault() ? 我应该return false吗?

Event.stopPropagation (Event.stopPropagation)

Suppose I want to handle a click event on an element.

假设我要处理元素上的click事件。

By default an event on a DOM element is fired on the specific element clicked (say, a button) and will be propagated to all its parent elements tree, unless it’s stopped.

默认情况下,在单击的特定元素(例如按钮)上会触发DOM元素上的事件,除非该事件被停止,否则它将传播到其所有父元素树中。

I want to make sure the event is handled in my event handler, and it will “stop” there.

我想确保该事件在我的事件处理程序中得到处理,并且将“在那里”停止。

You can stop the propagation by calling stopPropagation() method of an Event object, usually at the end of the event handler:

您可以通过通常在事件处理程序的结尾处调用Event对象的stopPropagation()方法来停止传播:

const link = document.getElementById('my-link')
link.addEventListener('mousedown', event => {
  // process the event
  // ...

  event.stopPropagation()
})

Event.preventDefault (Event.preventDefault)

Calling the preventDefault() method of the event object will cancel the default handling that the browser is programmed to execute.

调用事件对象的preventDefault()方法将取消浏览器编程为执行的默认处理。

Opening a new page on an a element click event, for example.

打开上一个新的页面a元素click事件,例如。

Or submitting a form on the submit event.

或在submit事件上提交form

Calling preventDefault() is what you need to do to completely customize the action. Perhaps by creating a fetch request to load some JSON instead of opening a new page on a link click.

要完全自定义动作,需要调用preventDefault() 。 也许是通过创建fetch请求以加载一些JSON而不是在链接单击上打开新页面来实现的。

Other event handlers defined on this same element will execute. Unless you call event.stopImmediatePropagation().

在相同元素上定义的其他事件处理程序将执行。 除非您调用event.stopImmediatePropagation()

返回false (Returning false)

This is especially confusing to former (or current) jQuery developers. In jQuery, returning false from an event handler automatically called Event.preventDefault and Event.stopPropagation for us.

这对于以前的(或当前的)jQuery开发人员尤其令人困惑。 在jQuery中,从自动为我们调用Event.preventDefaultEvent.stopPropagation的事件处理程序返回false

In vanilla JavaScript, return false in an event handler does nothing.

在原始JavaScript中,在事件处理程序中return false不会执行任何操作

翻译自: https://flaviocopes.com/events-stoppropagation-preventdefault/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值