当前位置:网站首页>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 advocate
UsekeyCode
( 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 :
addEventListener
The third parameter is passed intrue
It means that the capture phase triggers (Rarely used
)
If the incomingfalse
representative 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 .target
You 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()
}
})
边栏推荐
- JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
- kubeadm join时出现错误:[ERROR Port-10250]: Port 10250 is in use [ERROR FileAvailable--etc-kubernetes-pki
- Lekao: 22 year first-class fire engineer "technical practice" knowledge points
- Visual studio efficient and practical extension tools and plug-ins
- [ybtoj advanced training guidance] judgment overflow [error]
- spfa AcWing 851. spfa求最短路
- Anxiety of a 211 programmer: working for 3 years with a monthly salary of less than 30000, worried about being replaced by fresh students
- 2.6 using recursion and stack - [tower of Hanoi problem]
- China traffic sign detection data set
- Docker-compose配置Mysql,Redis,MongoDB
猜你喜欢
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
区间DP AcWing 282. 石子合并
arcgis js 4. Add pictures to x map
高性能纠删码编码
MySQL and PostgreSQL methods to grab slow SQL
China traffic sign detection data set
Sparkcontext: error initializing sparkcontext solution
Multiply LCA (nearest common ancestor)
JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
In development, why do you find someone who is paid more than you but doesn't write any code?
随机推荐
String palindrome hash template question o (1) judge whether the string is palindrome
AI mid stage technology research
Sub thread get request
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
Simple understanding of ThreadLocal
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
2.6 using recursion and stack - [tower of Hanoi problem]
分布式机器学习框架与高维实时推荐系统
CPU指令集介绍
单指令多数据SIMD的SSE/AVX指令集和API
The differences and relationships among port, targetport, nodeport and containerport in kubenetes
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
考研英语二大作文模板/图表作文,英语图表作文这一篇就够了
IPhone 6 plus is listed in Apple's "retro products" list
Redis introduction, scenario and data type
Intel internal instructions - AVX and avx2 learning notes
bellman-ford AcWing 853. 有边数限制的最短路
线性DP AcWing 896. 最长上升子序列 II
JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)