JS, we can add a listener event to a DOM object, the function is
AddEventListener ("click", Function () {},true);
It is easy to understand that the first parameter is the event type, such as Click, Touch (Touchstart),
The second argument is an event function,
For example, I add an alert function to a button.
Window.onload=function () {
document.getElementById ("Hello"). AddEventListener ("onkeydown", function () {
Alert ("Hello");
});
}
So what's the third parameter? This parameter is designed to capture the event and bubble, which is true when it is caught, false when bubbling.
What do you mean?
I give a simple example, I have two div and a button,button inside the Div2, div2 inside the DIV1. As shown
Click events are added to button, Div1, div2, Alert button, Div1, Div2, respectively.
Window.onload=function () {
document.getElementById ("Btn"). AddEventListener ("click", Function () {
Body ...
Alert ("Hello");
});
document.getElementById ("Div1"). AddEventListener ("click", Function () {
Alert ("Div1");
});
document.getElementById ("Div2"). AddEventListener ("click", Function () {
Alert ("Div2");
});
}
Then the question comes, I click button, also equivalent to click on Div1 and Div2, then, who first appear?
Intuitively speaking, who is on top, who is below.
Therefore, in JS is divided into two processing methods, bubbling and capture.
Bubbling: Triggering events from inside to outside, that is, the alert order is button, Div2, Div1.
Capture: Triggering an event from the outside, that is, the alert sequence is DIV1, Div2, button.
To bubble, set the third parameter of each listener event to false, which is the default value.
To capture, set the third parameter of each listener event to true.
All right, that's all. In order to better understand bubbles and captures, you can set the third parameter of three events casually, that is, set to TRUE or false when different,
Give the button a true,div1 to false and so on, the two concepts can be better understood according to the result.
JS in AddEventListener the third parameter involves event capture and bubbling