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.preventDefault
和Event.stopPropagation
的事件处理程序返回false
。
In vanilla JavaScript, return false
in an event handler does nothing.
在原始JavaScript中,在事件处理程序中return false
不会执行任何操作 。
翻译自: https://flaviocopes.com/events-stoppropagation-preventdefault/