1. event

In the browser client application platform , Most students are event driven , That is, something happens , Then make the corresponding action .

Browser events are signals of something happening . The elaboration of the event is not the focus of this article , Friends you don't know , You can visit W3school course   Get to know , This will help to better understand the following .

2. Bubbling mechanism

What is bubbling ?

Here is a picture you should understand , Bubbles begin to rise from the bottom , From deep to shallow , Up to the top . In the process of rising , Bubbles pass through different depths of water .

Correspondingly : This bubble is equivalent to our events here , And water is our whole dom Trees ; Events from dom The bottom of the tree Layer upon layer , Until it reaches dom The root node .

Simple case analysis

Here is a simple example to illustrate the bubbling principle :

Define a html, There are three simple ones dom Elements :div1,div2, span,div2 contain span,div1 contain div2; And they're all body Next :

 <span style="font-family:Microsoft YaHei;font-size:10px;"><body id="body">
<div id="box1" class="box1">
<div id="box2" class="box2">
<span id="span">This is a span.</span>
</div>
</div>
</body></span>

The interface prototype is as follows :

On this basis , We implement the following functions :

a.body add to click Event monitoring , When body Capture to event When an event is , Print out the time and time of the event The node information that triggers the event :

 <script type="text/javascript">
window.onload = function() {
document.getElementById("body").addEventListener("click",eventHandler);
}
function eventHandler(event) {
console.log(" Time :"+new Date(event.timeStamp)+" The node that generated the event :" + event.target.id +" Current node :"+event.currentTarget.id);
}
</script>

When we click in turn "This is span",div2,div1,body after , Output the following information :

Analysis of the above results :

      Whether it's body,body Child elements div1, still div Child elements div2, also span, When these elements are clicked click when , produces click event , also body Will capture , Then the corresponding event handler function is called . It's like bubbles in water coming up from the bottom , Events will also go up .

The schematic diagram of event delivery is as follows :

In a general way , There will be some information in the process of event transmission , These are part of the event : Time of event + Where it happened + Type of event + The current handler of the event + Other information ,

complete html The code is as follows :

 <span style="font-family:Microsoft YaHei;font-size:10px;"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<title>Insert title here</title>
<style type="text/css">
.box1 {
border: green 40px solid;
width: 300px;
height: 300px;
margin: auto;
} .box2 {
border: yellow 40px solid;
width: 220px;
height: 220px;
margin: auto;
} span {
position: relative;
left: 50px;
top: 50px;
background-color: rgba(128, 128, 128, 0.22);
}
</style> <script type="text/javascript">
window.onload = function() {
document.getElementById("body").addEventListener("click",eventHandler);
}
function eventHandler(event) {
console.log(" Time :"+new Date(event.timeStamp)+" The node that generated the event :" + event.target.id +" Current node :"+event.currentTarget.id);
}
</script> </head>
<body id="body">
<div id="box1" class="box1">
<div id="box2" class="box2">
<span id="span">This is a span.</span>
</div>
</div>
</body>
</html></span>

b. Bubble of termination events

We want to do this now , stay div1 When you click , eject " Hello , I'm the outermost layer div.", Click on div2 When , eject " Hello , I'm on the second floor div"; Click on span When , eject " Hello! , I am a span.".

From this we will have the following JavaScript fragment :

 <span style="font-family:Microsoft YaHei;font-size:10px;"><script type="text/javascript">
window.onload = function() {
document.getElementById("box1").addEventListener("click",function(event){
alert(" Hello! , I'm the outermost layer div.");
});
document.getElementById("box2").addEventListener("click",function(event){
alert(" Hello! , I'm on the second floor div.");
});
document.getElementById("span").addEventListener("click",function(event){
alert(" Hello! , I am a span.");
});
}
</script></span>

The above code is expected to click span When , There will be a pop-up " Hello! , I am a span." Yes , It does pop up a dialog like this :

However , It's not just this dialog that's going to come out , When you click OK , The following dialog boxes will pop up in turn :

That's clearly not what we want ! What we want is to point out who's showing who's information . Why does this happen ? The reason is the bubbling of events , Click on span When ,span It's going to bubble things up , As the parent node div2 and Grandfather's div1 You will also receive this event , And then there's an event response , Execute the response function . Now the problem is to find , But how to solve it ?

Method 1 : Let's consider a more visual situation : A bubble in the water is rising from the bottom , And you're in the water right now , I don't want this bubble going up , What shall I do? ?—— Prick it ! No bubbles , It's not going up . Similarly , For a node , If you don't want the events it's dealing with to continue bubbling up , We can stop bubbling :

In the corresponding processing function , Join in   event.stopPropagation()   , Terminate the broadcast distribution of the event , So the event stays in this node , It's not going out any more . Amend the above script fragment :

 <span style="font-family:Microsoft YaHei;font-size:10px;"><script type="text/javascript">
window.onload = function() {
document.getElementById("box1").addEventListener("click",function(event){
alert(" Hello! , I'm the outermost layer div.");
event.stopPropagation();
});
document.getElementById("box2").addEventListener("click",function(event){
alert(" Hello! , I'm on the second floor div.");
event.stopPropagation();
});
document.getElementById("span").addEventListener("click",function(event){
alert(" Hello! , I am a span.");
event.stopPropagation();
});
}
</script></span>

After this piece of code , Clicking on different elements will give different prompts , There won't be multiple pop-up boxes .

Method 2 : Event contains the node reference that initially triggered the event and Reference to the current processing event node , If the node only deals with the events triggered by itself , It's not self generated events that are not handled .event.target It's quoted to produce this event Object's dom node , and event.currrentTarget The current processing node is referenced , We can go through this Two target Whether it is equal or not .

such as span Click event , Produce a event Event object ,event.target Yes span Elements ,span When handling this event ,event.currentTarget It also points to span Elements , At this time, it is judged that the two are equal , The corresponding processing function is executed . And events pass to div2 When ,event.currentTarget become div2, At this time, the two are not equal , That is, the event is not div2 Of itself , No response processing logic .

 <span style="font-family:Microsoft YaHei;font-size:10px;"><script type="text/javascript">
window.onload = function() {
document.getElementById("box1").addEventListener("click",function(event){
if(event.target == event.currentTarget)
{
alert(" Hello! , I'm the outermost layer div.");
}
});
document.getElementById("box2").addEventListener("click",function(event){
if(event.target == event.currentTarget)
{
alert(" Hello! , I'm on the second floor div.");
}
});
document.getElementById("span").addEventListener("click",function(event){
if(event.target == event.currentTarget)
{
alert(" Hello! , I am a span."); }
});
}
</script></span>

Compare :

In terms of event delivery : One way is to cancel event bubbling , That is, when some nodes cancel bubbling , Events are no longer delivered ; The second way is not to stop bubbling , Filtering events that need to be handled , After the event is handled, it will continue to be delivered ;

Advantages and disadvantages :

One drawback of the method is : In order to display the corresponding information by clicking a specific element , Method 1 requires that the child elements of each element must also terminate the bubbling of events , That is, it is strongly related to other elements in function , Such an approach would be fragile . such as , If span Element's handler does not perform bubble termination , Then the event will spread to div2 On , This will cause div2 A reminder of ;

The second disadvantage of the method is : Method 2 adds an event listening and processing function for each element , The logic of event handling is very similar , That is, there are judgments if(event.target == event.currentTarget), So there's a lot of code redundancy , Now it's three elements. OK , When there is 10 How many? , What about hundreds of them ?

There is also a processing function for each element , Increase the complexity of logic and code to a certain extent .

Let's analyze method two : The principle of method two is After the element receives the event , Judge whether the event meets the requirements , Then do the corresponding treatment , And then the events continue to bubble up ;

Since the event is bubbling , Can a parent node handle events in a unified way , By judging where the event happened ( That is, the node where the event is generated ), And then make corresponding treatment ? The answer is yes , Now by giving body Element to add event listening , And then by judgment event.target And then for different target Produce different behaviors .

Refactoring the code of method 2 :

 <script type="text/javascript">
window.onload = function() {
document.getElementById("body").addEventListener("click",eventPerformed);
}
function eventPerformed(event) {
var target = event.target;
switch (target.id) {
case "span":
alert(" Hello! , I am a span.");
break;
case "div1":
alert(" Hello! , I'm on the second floor div.");
break;
case "div2":
alert(" Hello! , I'm the outermost layer div.");
break;
}
}
</script>

The result would be to click on different elements , Only pop up the corresponding prompt , There won't be extra hints .

Through the above methods , Let's put the processing function that every element should have , All to his grandfather body Elements to complete , in other words ,span,div2,div1 Delegate your response logic to body, Let it do the logic , I don't realize the corresponding logic , This mode , It's called event delegation .
          Here is a schematic diagram :

Javascript More articles on event bubbling mechanism

  1. analysis Javascript Event bubbling mechanism

    This resource is quoted from : analysis Javascript Event bubbling mechanism - My procedural life - Blog channel - CSDN.NET http://blog.csdn.net/luanlouis/article/details/ ...

  2. analysis Javascript Event bubbling mechanism ( turn ) In this paper, from :http://blog.csdn.net/luanlouis/article/details/23927347

    In this paper, from :http://blog.csdn.net/luanlouis/article/details/23927347 1. event In the browser client application platform , Most students are event driven , That is, something happens , however ...

  3. analysis Javascript Event bubbling mechanism ( turn )

    In this paper, from :http://blog.csdn.net/luanlouis/article/details/23927347 1. event In the browser client application platform , Most students are event driven , That is, something happens , however ...

  4. JavaScript Event bubbling mechanism and prevent event bubbling and default Events

    One . Stop the event from bubbling : 1.html To add return false 2.js To add return false 3.IE Next :window.event.cancelBubble = true:  FF Next :event ...

  5. JavaScript The event bubbling mechanism in

    Event bubbling mechanism The conditions under which the event bubbled : When the same event handler is set for multiple nested elements , They will trigger event bubbling . In the bubble of events , The innermost element will first trigger its event , Then the next element in the stack triggers the event , And so on , Until we get to the most ...

  6. javascript Details of event delegation mechanism

    In terms of personal front-end job interview experience ,javascript Event delegation is one of the most frequently asked questions , Be familiar with the event delegation and be able to understand your understanding of javascript The degree of mastery . The interviewer may ask a question , Now there is 5 individual li To do event , Need to achieve when the point ...

  7. Talking about js The event bubbling mechanism of

    Many people have heard of ,js The event bubbling mechanism of , Actually , This statement is more vivid , It's a bubble under the water , The process of bubbling to the surface . that js The bubble mechanism of events , It's just one. DOM Trees , The process of going up one level at a time , In the end document ...

  8. turn :JavaScript Brief introduction and application of event bubbling

    ( This article is reproduced elsewhere ) JavaScript Brief introduction and application of event bubbling   One . What is event bubbling Trigger some kind of event on an object ( For example, click onclick event ), If this object defines a handler for this event , Then this event will call this process ...

  9. JavaScript Event bubbling and event delegation

    JavaScript Event bubbling and event delegation Fu Jianyu  - 2 comments Contact JavaScript Soon , I didn't learn too much . Xiaoyu is used to sharing what he has learned . On the one hand, strengthen your impression , On the one hand, we can make our own experience ...

Random recommendation

  1. [LeetCode] Paint House II Painting the house two

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  2. stay MySQL in , How to calculate the median of a set of data ?

    To get the median of a set of data ( For example, the median income of a region or a company ), Let's first break this down into 3 Small tasks : Sort the data , And give each row of data its ranking in all data . Find the median ranking number . Find the value of the middle ranking ...

  3. 11.Android Common dialog box AlertDialog Study

    (1) First, let's write a simple AlertDialog Dialog box , To create a AlertDialog, You use AlertDialog.Builder Medium create() Method , Then create a dialog box to set the properties of the dialog box , such as ...

  4. Tomcat Set the default startup project and Java Web Project settings default startup page

    Tomcat Set the default startup project Tomcat Set the default startup project , seeing the name of a thing one thinks of its function , That is, you can enter... In the address bar of the browser ip:8080, Access to our projects . The specific operation is as follows : 1. open tomcat Installation root of , find Tom ...

  5. android Official course in Chinese

    Thank you for your silent dedication :) https://github.com/kesenhoo/android-training-course-in-chinese http://hukai.me/android ...

  6. USB Enumeration process

    Windows Yes USB The enumeration process flow chart of the device is shown in Fig 1 Shown : chart 1 WP8 Of USB The function supports only one configuration , Three interfaces , That is, there are the following fields : Of the device descriptor bNumConfigurations=1, Configuration descriptor ...

  7. How to integrate XML convert to XSD(XML Schema) file

    take xml Replace with xsd, The prerequisite is that Visual Stutio 1) Input cmd In the run window 2) take xsd The path to join path Variable set path=%path%;C:\Program File ...

  8. SpringBoot series : All configuration properties and official documents

    Spring Boot General configuration parameters https://docs.spring.io/spring-boot/docs/current/reference/html/common-application- ...

  9. Script error. resolvent

    1. add to  crossorigin="anonymous"  To script label <script src="https://xxx.com/xxx.js" ...

  10. angular Configure the routing / Subpage +vue Configure the routing / Subpage

    1. stay vue.js Components can be reused in , And then I recently configured several subpages stay This file configures routing , The configuration of subpages is the same as others , It's just path Different .   routes: [     { path: '/',       ...