Incident triggering (bubbling mechanism) and detailed explanation of the solution

Event bubbling mechanism In
layman's terms, it means that the parent element and the child element have a method respectively, and the method of the parent element is also triggered when the child element method is triggered.

As shown in the figure below,
create a div, create a button element under the div, bind a click event named divHandler to the div, bind a click event
named btnHandler to the button

Insert picture description here

We hope to realize
that it will print out when the div field is clicked (click the inner div click event)
when the button is clicked (click the btn button)
Insert picture description here

First click on the div,
you can see that the console on the right is printed (clicking on the click event of the inner div).
Insert picture description here
Click the button.
You can see that not only the click method of the button is triggered, but the click method of the div is also triggered.

Insert picture description here

The above is the manifestation of the bubbling mechanism of the event

Here are two solutions:
1. Add (.stop) at the bottom of the event trigger
2. Add a restriction mechanism for div (.self)

1. Add stop at the bottom of the event

(The stop method can completely prevent the bubbling mechanism of the event)

Insert picture description here

2. Add a restriction mechanism to the div

The function of the self method is: the event function is triggered only when the current element is clicked
(this method solves the defect of bubbling)
Insert picture description here

Self solves the defect of the bubbling mechanism

Add self to the outermost div, and the
inner div will not be processed

Insert picture description here

Click on the outer div

Insert picture description here

Click on the inner div

Insert picture description hereClick the button
Insert picture description here

You can see that when the button event is triggered, the inner div event is also triggered.
Only the outer div with self added does not trigger the event.

The above is the summary of the bubbling mechanism of the incident and the solution

Guess you like

Origin blog.csdn.net/Hambur_/article/details/109389587