Home >Web Front-end >JS Tutorial >Detailed analysis of the third parameter useCapture (Boolean) of addEventListener()_Basic knowledge
Example
If you click the mouse on d3, the event flow is like this:
The capture phase detects whether there is an event handler with useCapture as true at div1. If there is, execute the program and then process div2 similarly.
Target stage At div3, it is found that div3 is the node clicked by the mouse, so this is the target stage. If there is an event handler, the program will be executed, regardless of whether useCapture is true or false.
In the bubbling phase, detect whether there is an event handler with useCapture set to false at div2. If there is, execute the program and then process div1 similarly.
addEventListener has three parameters: the first parameter represents the event name (excluding on, such as "click"); the second parameter represents the function to receive event processing; the third parameter is useCapture, which is explained in this article.
outDiv.addEventListener("click", function () { info.innerHTML = "outDiv" "
"; }, false);
middleDiv.addEventListener("click", function () { info .innerHTML = "middleDiv" "
"; }, false);
inDiv.addEventListener("click", function () { info.innerHTML = "inDiv" "
"; }, false );
The above is the code we tested. The order of triggering is determined based on the display of info. There are three addEventListeners, and the optional values of useCapture are true and false, so 2*2*2, we can get 8 different programs.
•When all are false, the triggering order is: inDiv, middleDiv, outDiv;
•When all are true, the triggering order is: outDiv, middleDiv, inDiv;
•When outDiv is true and others are false, the triggering order is: outDiv, inDiv, middleDiv;
•When middleDiv is true and others are false, the triggering order is: middleDiv, inDiv, outDiv;
•……
Finally came to the following conclusion:
•The triggering order of true is always before false;
•If multiple ones are true, the outer layer is triggered before the inner layer;
•If multiple ones are false, the inner layer is triggered before the outer layer.