当前位置:网站首页>DOM -- event chain, event bubble and capture, event proxy
DOM -- event chain, event bubble and capture, event proxy
2022-07-28 07:02:00 【Hahaha~】
One 、 Chain of events
The three stages of the event :
Capture phase : Structurally ( Not visually ) Elements of nested relationships , There will be event capture capabilities , That is, the same event is captured from the parent element to the child element ( Event source element )( The top-down )
Target stage : Events continue to pass until the target node , Finally, this event is triggered on the target node
bubbling phase : Structurally ( Not visually ) Elements of nested relationships , There will be event bubbling functions , That is, the same event bubbles from the child element to the parent element ( Bottom up )

notes : The process of event transmission It is only related to the structure of the document tree It has nothing to do with the stacking effect displayed on the interface
Two 、 Event capture and bubbling
( One ) Event execution mode :
a) event Capture when : The parent element triggers , Trigger after child element
- Top down trigger
- stay addEventListener The third parameter is set to true Execute the event when capturing
b) event Bubbling when : Child elements trigger first , Triggered after the parent element W3C standard The default is event bubbling
- stay onclick/attach and addEventListener The third parameter is set to false When bubbling, execute the event
c) There can only be A phase Trigger program execution
d) If the event passes through all elements and is not processed , This event will disappear
e) The whole event processing process , There is one event Event objects propagate throughout the event process (W3C standard ,ie8 There is no )
f) Prevent event delivery The only way is to stop the event from bubbling
Question and answer :
addEventListener The third parameter of is true Is it to prevent the transmission of events or false?
answer : Will not prevent the transmission of events : because true Capture phase triggers false The bubbling phase triggers
( Two ) Prevent bubbling and system default events
1、 Stop the event from bubbling :
event.stopPropagation() :W3C standard I won't support it ie9 The following versions
stopImmediatePropagation() :
- Support stopPropagation You can also use
- It will not only prevent the event from bubbling to the parent element It will also block other event handlers of the same event on the same node ( When the priority is lower than it or there are multiple handlers for the same element and event )
event.cancelBubble=true: ie8 And ie8 The following are available
notes : None of the above can prevent default system events
2、 Block system ( browser ) Default event :
Default event —— Form submission ,a Tag jump , Right click menu and so on
event.preventDefault(): W3C standard IE9 The following are not compatible
return false: An event is registered as an object property to take effect use addEventListener/attachEvent Don't take effect
event.returnValue=false: compatible IE
notes : The above is only for The same thing
Non bubbling events :focus,blur,change,submit,reset,select etc.
( 3、 ... and ) Interview questions
In a DOM Bind two click events at the same time : One uses capture , One with bubbles . The event will be executed several times , Bubble or capture first ?
answer :
a) The DOM If the event on is triggered , I'll do it twice ( The number of executions equals the number of bindings )
b) If it's time to DOM It's the target element , In the event binding order , Don't differentiate between bubbling / Capture
c) If it's time to DOM It's a non target element in the event flow , Then execute the capture first , Perform bubbling after
3、 ... and 、 Event agent
( One ) Concept :
- Event agent is also called event delegation , yes JS Common skills of binding events in
- Delegate the event that needs to be bound to the parent element , Let the parent element listen for events , Use the bubbling mechanism to trigger the event
- Using events target Properties and bubbling mechanism
( Two ) Case study
demand :1. Click the button to add a new div The content is “new div5”
2. Click on each div Print its contents
<style>
.box1{
width: 200px;
background-color:blueviolet;
}
.box2{
height: 40px;
line-height: 40px;
background-color:pink;
margin: 10px;
text-align: center;
}
</style>
<div class="box1">
<div class="box2">div1</div>
<div class="box2">div2</div>
<div class="box2">div3</div>
<div class="box2">div4</div>
</div>
<button onclick="add()"> Click Add div</button>- The code to realize the requirements without event agent is as follows :
function add(){
var box1=document.querySelector(".box1")
var box2=document.createElement("div")
box2.innerHTML="new div5"
box2.className="box2"
box1.appendChild(box2)
}
var box2s=document.querySelectorAll(".box2")
box2s.forEach(el=>{
el.addEventListener("click",function(e){ // To every one. div Bind click event
console.log(this.innerHTML)
})
})
/* The disadvantages of this design
Because each iteration will bind an event and generate new functions to achieve the same business requirements, the performance consumption is higher
*/
Print the results :

Result analysis :
Click add new div No click event is triggered The console cannot print this div The content of
So the static event binding is after adding new elements dynamically , New elements cannot trigger events
- Code for implementing requirements with event agents
var box1=document.querySelector(".box1")
box1.addEventListener("click",function(e){
console.log(e.target.innerHTML)
})
/* Bind point events to parent elements When the click event of the parent element is triggered utilize target Locate the specific child element you hit Then print its contents
Dynamically added new div5 You can also print out the content
*/Print the results :

Result analysis :
Click add new div Triggered a click event The console prints the div The content of --new div5
Bind only one element ( Parent element ) You can realize the click Print requirements of all sub elements
Problem solved :
- Bind the same event repeatedly
- When Binding static events, add elements dynamically The added element has no bound event
( 3、 ... and ) Advantages and disadvantages :
advantage :
- Save a lot of memory , Reduce performance consumption , Improve overall performance
- Events can be applied to dynamically added child elements , It can reduce the repeated registration of events
shortcoming :
- Improper use can cause events to trigger when they should not
- Some events ( Having no bubbling characteristics ) Cannot use event proxy
Events suitable for event proxy :click、mousedown、mouseup、keyup、keydown、keypress etc.
边栏推荐
- How about air conduction Bluetooth headset? It's the most worthwhile air conduction headset to start with
- OSI seven layer model
- Custom component -- pure data field & component life cycle
- Hdu-5805-nanoape loves sequence (thinking questions)
- VSphere esxi 7.0 update 3 release notes
- Servlet
- [learning notes] thread creation
- KVM热迁移
- 360 compatibility issues
- Build php7 private warehouse
猜你喜欢

MOOC翁恺C语言 第六周:数组与函数:1.数组2.函数的定义与使用3.函数的参数和变量4.二维数组

MySQL master master

Applets: WSX scripts

Shell script -- program conditional statements (conditional tests, if statements, case branch statements, echo usage, for loops, while loops)

QGraphicsView提升为QChartView

Custom component -- pure data field & component life cycle

Vmware workstation configuration net mode

iptables防火墙

Network - transport layer (detailed version)

Which brand of air conduction earphones is better? These four should not be missed
随机推荐
As a result, fill in the birthday candles
MOOC翁恺C语言 第六周:数组与函数:1.数组2.函数的定义与使用3.函数的参数和变量4.二维数组
Hdu-1159-commonsubsequence (LCS longest common subsequence)
DHCP原理与配置
QGraphicsView提升为QChartView
shell脚本——正则表达式
QT uses MSVC compiler to output Chinese garbled code
How about air conduction Bluetooth headset? It's the most worthwhile air conduction headset to start with
Create, traverse and search nodes as required for single linked list
Upload and download files from Ubuntu server
NFS 共享存储服务
Tcp/ip five layer model
What's a good gift for Tanabata? Niche and advanced product gift recommendation
Scratch command
Iptables firewall
DHCP principle and configuration
Understanding of C language EOF
shell脚本——sort、uniq、tr、数组排序、cut、eval命令配置
Technology sharing | how to simulate real use scenarios? Mock technology to help you
MOOC翁恺C语言第五周:1.循环控制2.多重循环3.循环应用