Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - Why is 'false' used after this simple addEventListener function?

What is the false for at the end? Thanks.

window.addEventListener('load', function() {
  alert("All done");
}, false);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I checked MDN too, but I still didn't understand what the useCapture was for, so this answer is for those who still don't get it after having checked the official documentation.

So first of all, the following happens in almost all browers:

In all browsers, except IE<9, there are two stages of event processing.

The event first goes down - that’s called capturing, and then bubbles up . This behavior is standartized in W3C specification.

which means no matter what you set the useCapture to, these two event phases always exist.

This picture shows how it works.

enter image description here

According to this model, the event:

Captures down - through 1 -> 2 -> 3.

Bubbles up - through 3 -> 2 -> 1.

Then comes your question. The 3rd param called useCapture indicates on which of the two phases you want your handler to handle the event.

useCapture = true

The handler is set on the capturing phase. Events will get to it before getting to its children.

useCapture = false.

The handler is set on the bubbling phase. Events will get to it after getting to its children.

which means that if you write code like this:

child.addEventListener("click", second);
parent.addEventListener("click", first, true);

when clicking child element, first method will be called before second.

By default, the useCapture flag is set to false which means you handler will only be called during event bubbling phase.

For detailed info, click this reference link and this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...