Explain useCapture of the three parameters of addEventListener

  • 2020-05-17 04:45:18
  • OfStack

addEventListener has three parameters: the first parameter represents the event name (without on, such as "click"); The second parameter represents the function to receive event handling; The third parameter, useCapture, is explained in this article.

 
<div id="outDiv">
  <div id="middleDiv">
    <div id="inDiv"> Click here. </div>
  </div>
</div>
<div id="info"></div>


var outDiv = document.getElementById("outDiv");
var middleDiv = document.getElementById("middleDiv");
var inDiv = document.getElementById("inDiv");
var info = document.getElementById("info");
outDiv.addEventListener("click", function () { info.innerHTML += "outDiv" + "<br>"; }, false);
middleDiv.addEventListener("click", function () { info.innerHTML += "middleDiv" + "<br>"; }, false);
inDiv.addEventListener("click", function () { info.innerHTML += "inDiv" + "<br>"; }, false);

The above is our test code, according to the display of info to determine the order of triggering, there are 3 addEventListener, and useCapture optional values are true and false, so 2*2*2, you can get 8 different segments of the program.

The & # 8226; When all are false, the trigger sequence is: inDiv, middleDiv, outDiv;
The & # 8226; When all are true, the trigger sequence is: outDiv, middleDiv, inDiv;
The & # 8226; When outDiv is true and others are false, the trigger sequence is outDiv, inDiv and middleDiv.
The & # 8226; When middleDiv is true and others are false, the order of triggering is: middleDiv, inDiv, outDiv;
The & # 8226; ...


The conclusion is as follows:

The & # 8226; true always triggers before false;
The & # 8226; If more than one is true, the trigger of the outer layer precedes that of the inner layer.
The & # 8226; If more than one is false, the trigger of the inner layer precedes that of the outer layer.

That's all for this article, I hope you enjoy it.


Related articles: