Home >Web Front-end >JS Tutorial >Code analysis of event bubbling ratio
This article mainly introduces the code analysis of event bubbling ratio bubble. It has certain reference value. Now I share it with you. Friends in need can refer to it.
The concept of bubble is when When a child element triggers an event, the corresponding ancestor element will also trigger the same event
(provided that the parent element has also added the same event)
eg: The son has an onclick ancestor ten The eighth generation also has onclick
When clicking on the son, the click event of the eighteenth generation of the ancestor will also be triggered
Sometimes this situation will cause many problems, so we must prevent bubbling
Only clicked elements trigger events
Not all events will bubble
onblur onfocus onload onerror No
In fact, there are three processes for triggering events: Capture phase--->In target phase---->Bubbling phase
Standard browser bubble order child elements-->Parents-->body-->document-- ->window
IE child element-->parent-->body-->document
Next, it is very easy to write the code. Just do a compatibility process
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>阻止冒泡</title> </head> <body> <input type="button" id="cancelBubble" value="取消冒泡"/> <script type="text/javascript"> var btn=document.getElementById("cancelBubble"); document.onclick=function(){ alert("冒泡"); } btn.onclick=function(event){ var event=event||window.event;//兼容 if(event && event.stopPropagation){ event.stopPropagation(); } else{ //IE 678 event.cancelBubble=true; } alert("没有冒泡"); } </script> </body> </html>
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Analysis of how NodeJS operates the message queue RabbitMQ
How JavaScript implements the file download function
The above is the detailed content of Code analysis of event bubbling ratio. For more information, please follow other related articles on the PHP Chinese website!