简体   繁体   English

事件侦听器之后的“,true);”有什么作用?

[英]What does “ ,true);” after an event listener do?

I came across this code: 我碰到了这段代码:

window.addEventListener('keydown',function(e){
keyState[e.keyCode] = true;
},true);

And I don't get what the ",true);" 而且我不明白“,true);” part does. 部分。 Could somebody please explain its purpose? 有人可以解释一下它的目的吗? Thanks in advance! 提前致谢!

From MDN's notes on addEventListener , that is the useCapture flag: MDN关于addEventListener的注释中 ,它是useCapture标志:

useCapture Optional useCapture 可选

A Boolean that indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. 一个布尔值,指示此类型的事件将被分派给注册的侦听器,然后才被分派给DOM树中其下的任何EventTarget。 Events that are bubbling upward through the tree will not trigger a listener designated to use capture. 在树上冒泡的事件不会触发指定使用捕获的侦听器。 Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. 当两个元素都注册了该事件的句柄时,事件冒泡和捕获是传播在嵌套在另一个元素内的元素中发生的事件的两种方式。 The event propagation mode determines the order in which elements receive the event. 事件传播模式确定元素接收事件的顺序。

You can catch event in bubbling phase or in capturing phase. 您可以在冒泡阶段或捕获阶段捕获事件。

window.addEventListener('keydown',function(e){
    keyState[e.keyCode] = true;
},true);

In your code snippet true is useCapture flag, meaning that we specify capturing phase. 在您的代码段中, trueuseCapture标志,这意味着我们指定了捕获阶段。

The next question probably would be What is event bubbling and capturing? 下一个问题可能是事件冒泡和捕获什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM