Event capture model and bubble model instance analysis in js
The specific implementation method is as follows:
Instance 1:
The Code is as follows:
<Html>
<Head>
<Script type = "text/javascript">
Window. onload = function (){
Document. getElementById ('par'). addEventListener ('click', function () {alert ('par') ;}, true );
Document. getElementById ('son'). addEventListener ('click', function () {alert ('son') ;}, true );
}
</Script>
<Style type = "text/css">
# Par {width: 300px; height: 200px; background: gray ;}
# Son {width: 200px; height: 100px; background: green ;}
</Style>
</Head>
<Body>
<Div id = "par">
<Div id = "son"> </div>
</Div>
</Body>
</Html>
Instance 2:
The Code is as follows:
<Html>
<Head>
<Script type = "text/javascript">
Window. onload = function (){
Document. getElementById ('par'). addEventListener ('click', function () {alert ('par ');});
Document. getElementById ('son'). addEventListener ('click', function () {alert ('son ');});
}
</Script>
<Style type = "text/css">
# Par {width: 300px; height: 200px; background: gray ;}
# Son {width: 200px; height: 100px; background: green ;}
</Style>
</Head>
<Body>
<Div id = "par">
<Div id = "son"> </div>
</Div>
</Body>
</Html>
AddEventListener: The third parameter is optional. The default parameter is false, indicating the bubble model. That is, the minimum layer is triggered first (div with id of son). If the parameter true is added, the capture model (from html --> body ---> div) is triggered at this level.
The html code of instance 1 has two divs. A small div is contained in a large div. When you click a small div, the alert ('par') event is triggered first; then trigger the entire alert ('son. Instance 2 is the opposite.
If the event is triggered using the "object. onclick" attribute, the bubble model is used.
IE does not support addEventListener, but uses attachEvent. However, attachEvent does not support the third parameter. It does not capture the model.
I hope this article will help you design javascript programs.