This article describes the event capture model and bubble model in js. Share it for your reference.
The specific implementation method is as follows:
Example 1:
Copy the code 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>
Example 2:
Copy the code 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 an optional parameter, which is false by default, indicating the bubble model, that is, the smallest layer is triggered first (div with id is son); and if true parameter is added, it means that it is the capture model (from html-->body--->div), triggering according to such a level.
The html code of Example 1 has two divs. The small div is contained in the large div. When clicking on the small div, the alert('par') event will first be triggered; and then the alert('son') whole piece will be triggered. Example 2 is exactly the opposite.
If the "Object.onclick" attribute is used to trigger the event, the bubble model is used.
IE does not support addEventListener, but uses attachEvent. But attachEvent does not support the third parameter, it does not capture the model.
I hope this article will be helpful to everyone's JavaScript programming.