当前位置:网站首页>Js7day (event object, event flow, event capture and bubble, prevent event flow, event delegation, student information table cases)
Js7day (event object, event flow, event capture and bubble, prevent event flow, event delegation, student information table cases)
2022-07-02 12:41:00 【By the Difeng River】
List of articles
Event object
Get event object
What is the event object ?
It's also an object , This object contains the relevant information when the event is triggered
for example : Mouse click event , The event object stores information such as where the mouse point isHow to get ?
Bound in event The first parameter of the callback function Namely Event object
It is generally namedevent、ev、e
Some common properties
type
Get the current event typeclientX/clientY
Gets the position of the cursor relative to the upper left corner of the browser visible windowoffsetX/offsetY
Gets the cursor relative to the current DOM The position of the upper left corner of the elementkey
The value of the keyboard key pressed by the user
Now?Do not advocateUsekeyCode( obsolete )
img {
position: absolute;
top: 0;
left: 0;
}
img Use absolute positioning
<img src="./images/tianshi.gif" alt="">
<script>
let img = document.querySelector('img')
document.addEventListener('mousemove', function (e) {
// Keep getting the current mouse coordinates
// Give the coordinates to the picture ( Don't forget the unit )
// img.style.left = '100px'
img.style.left = e.pageX - 50 + 'px'
img.style.top = e.pageY - 40 + 'px'
})

Add code :
area.addEventListener('keyup', function (e) {
// Do not use keydown, When the keyboard pops up , Execute again, otherwise area Li will accept enter character , Lead to area.value=1
if (e.key == 'Enter') {
// yes enter Key only
send.click()
}
})
Flow of events
- Flow of events It refers to the flow path during the complete execution of the event : Capture first, then bubble

Event capture concept :
from DOM The root element of starts to execute the corresponding event ( From the outside to the inside )
- Event capture needs to write corresponding code to see the effect
- Code :
DOM.addEventListener( Time type , Event handler , Whether to use capture mechanism )
- explain :
addEventListenerThe third parameter is passed intrueIt means that the capture phase triggers (Rarely used)
If the incomingfalserepresentative The bubbling phase triggers , The default isfalse
If used L0 Event monitoring , Then there is only the bubbling stage , No capture
Event bubble concept :
When an element's event is triggered , The same event will be in the All ancestral elements in Triggered in turn . This process is called Event Bubbling
Simple understanding : When an element triggers an event , The event with the same name of all parent elements will be called up in turn
Event bubbling exists by default
Case study :
<script>
let fa = document.querySelector('.father')
let son = document.querySelector('.son')
son.addEventListener('click', function () {
alert(' I'm a son ')
})
fa.addEventListener('click', function () {
alert(' I'm daddy ')
})
</script>
Click on the son area , Pop up one by one : I'm a son , I'm daddy ( Pass in true, On the contrary )
Stop the flow of events :
Because bubble mode exists by default , Therefore, it is easy for events to affect parent elements
- If you want to limit the event to the current element , You need to stop the flow of events
- To stop the flow of events, you need to get the event object
- grammar :
Event object .stopPropagation()
- This method can block the flow and propagation of events , Not just in the bubbling phase , The capture phase is also effective
Example :
<script>
let fa = document.querySelector('.father')
let son = document.querySelector('.son')
fa.addEventListener('click', function () {
alert(' I'm daddy ')
})
son.addEventListener('click', function (e) {
alert(' I'm a son ')
e.stopPropagation()
})
</script>
Click on the son area , Pop only : I'm a son .
Same mouse over event :
mouseover and mouseout There will be bubbling effect
mouseenter and mouseleave No bubbling effect ( recommend )
<script>
let fa = document.querySelector('.father')
let son = document.querySelector('.son')
fa.addEventListener('mouseover', function () {
console.log(111)
})
</script>
The mouse is inside the parent element , Move between parent and child elements , It will continue to output :111( Change to mousenter Just fine )
Two kinds of ( Monitoring events ) The difference between registration Events :
Tradition on register (L0)
- Same object , The events registered later will Cover Previously registered events ( The same thing )
- direct
=null( such asbtn.onclick=null), You can unbind events - All are bubbling phase Executive
Event listening registration (L2)
- grammar :
addEventListener( Event type , Event handler , Whether to use capture ) - Events registered later Will not cover Previously registered events ( The same thing )
- Can pass The third parameter To determine whether it is executed in the bubble or capture phase
- If you want to unbind events , You have to use
removeEventListener( Event type , Event handler , Get capture or bubbling stage ) - Anonymous functions cannot be unbound
btn.addEventListener('click', add)
function add() {
// Name the function , Anonymous functions cannot be unbound
alert(' for the first time ')
}
btn.removeEventListener('click', add)
Event delegation
Event delegation is the knowledge and skill to solve some development needs by using the characteristics of event flow
summary :
- advantage : Add an event to the parent element ( Can improve performance )
- principle : Event delegation actually takes advantage of the characteristics of event bubbling
- Realization :
Event object .targetYou can get the element that actually triggers the event
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
let ul = document.querySelector('ul')
ul.addEventListener('click', function (e) {
(e.target.style.color = 'red') // The core
})
</script>

Student information sheet case
The difficulty is how to delete , Event delegation is used , That is to monitor the whole big tbody, Looking for the click to delete belongs to tbody Which row of data in .
If you add listeners to each line in a stupid way , It's hard to achieve , And the performance is not good .
I didn't expect to use e.target.tagName Determine whether the clicked element is deleted . Also give a Add one id marked id="${i}" To delete the array .

js Code :
// 1. Prepare the data of the data back-end
let arr = [
{
stuId: 1001, uname: ' Ouyang batian ', age: 19, gender: ' male ', salary: '20000', city: ' Shanghai '},
{
stuId: 1002, uname: ' Linghu batian ', age: 29, gender: ' male ', salary: '30000', city: ' Beijing '},
{
stuId: 1003, uname: ' Zhuge batian ', age: 39, gender: ' male ', salary: '2000', city: ' Beijing '},
]
// Get parent element tbody
let tbody = document.querySelector('tbody')
// Add data button
// Get input button
let add = document.querySelector('.add')
// Get the elements of each form
let uname = document.querySelector('.uname')
let age = document.querySelector('.age')
let gender = document.querySelector('.gender')
let salary = document.querySelector('.salary')
let city = document.querySelector('.city')
// Rendering function Render the data in the array to the page
function render() {
// Kill the previous data first Give Way tbody The original inside tr None
tbody.innerHTML = ''
// Rendering new data
// Render according to the number of pieces of data tr
for (let i = 0; i < arr.length; i++) {
// 1. establish tr
let tr = document.createElement('tr')
// 2.tr Put the content in it
tr.innerHTML = ` <td>${
arr[i].stuId}</td> <td>${
arr[i].uname}</td> <td>${
arr[i].age}</td> <td>${
arr[i].gender}</td> <td>${
arr[i].salary}</td> <td>${
arr[i].city}</td> <td> <a href="javascript:" id="${
i}"> Delete </a> </td> `
// 3. hold tr Append to tobdy Parent element .appendChild( Subelement )
tbody.appendChild(tr)
}
}
// The function is called when the page is loaded
render()
add.addEventListener('click', function () {
// alert(11)
// Get the value in the form Later added to Array arr use push Method
arr.push({
// Get the student number of the last data in the array 1003 + 1
stuId: arr[arr.length - 1].stuId + 1,
uname: uname.value,
age: age.value,
gender: gender.value,
salary: salary.value,
city: city.value
})
// console.log(arr)
// Re render our function
render()
// Restore all form data
uname.value = age.value = salary.value = ''
gender.value = ' male '
city.value = ' Beijing '
})
// Delete operation , What is deleted is also the data in the array , But we use event delegation ( difficulty !!!)
tbody.addEventListener('click', function (e) {
// alert(11)
// We can only click on the link a , Delete only
// Then how do we know you clicked a Well ?
// We can only click the link to delete
// console.dir(e.target.tagName)
if (e.target.tagName === 'A') {
// alert(' You clicked on the link ')
// Delete operation Delete The data in the array arr.splice( Where to start deleting ,1) to a Add one id marked id="${i}"
// I want to get a Of id need
// console.log(e.target.id)
arr.splice(e.target.id, 1)
// Re render our function
render()
}
})
边栏推荐
- Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
- Fluent fluent library encapsulation
- There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes
- 哈希表 AcWing 840. 模拟散列表
- 单指令多数据SIMD的SSE/AVX指令集和API
- Drools dynamically add, modify, and delete rules
- The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
- CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
- 8A 同步降压稳压器 TPS568230RJER_规格信息
- 计数类DP AcWing 900. 整数划分
猜你喜欢
随机推荐
防抖 节流
浏览器存储方案
async/await 异步函数
Record the range of data that MySQL update will lock
drools执行完某个规则后终止别的规则执行
The differences and relationships among port, targetport, nodeport and containerport in kubenetes
[I'm a mound pytorch tutorial] learning notes
Is the neural network (pinn) with embedded physical knowledge a pit?
Sweetheart leader: Wang Xinling
ArrayList与LinkedList效率的对比
基于STM32的OLED 屏幕驱动
Mui WebView down refresh pull-up load implementation
区间DP AcWing 282. 石子合并
Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
MySQL and PostgreSQL methods to grab slow SQL
AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
Dijkstra AcWing 850. Dijkstra求最短路 II
Drools dynamically add, modify, and delete rules
哈希表 AcWing 840. 模拟散列表
CPU指令集介绍









