当前位置:网站首页>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()
}
})
边栏推荐
- 计数类DP AcWing 900. 整数划分
- 区间DP AcWing 282. 石子合并
- 线性DP AcWing 899. 编辑距离
- CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
- Docsify deploy IIS
- Direct control PTZ PTZ PTZ PTZ camera debugging (c)
- 哈希表 AcWing 841. 字符串哈希
- Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
- 怎样写一篇赏心悦目的英文数学论文
- This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry
猜你喜欢

防抖 节流

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

VLAN experiment

kubenetes中port、targetPort、nodePort、containerPort的区别与联系

Openssh remote enumeration username vulnerability (cve-2018-15473)

Redis sentinel mechanism and configuration
![[FFH] little bear driver calling process (take calling LED light driver as an example)](/img/e7/153ae9f1befc12825d277620049f9d.jpg)
[FFH] little bear driver calling process (take calling LED light driver as an example)

drools中then部分的写法

Dijkstra AcWing 850. Dijkstra求最短路 II

计数类DP AcWing 900. 整数划分
随机推荐
kubenetes中port、targetPort、nodePort、containerPort的区别与联系
上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
线性DP AcWing 902. 最短编辑距离
深拷贝 事件总线
arcgis js 4.x 地图中加入图片
[I'm a mound pytorch tutorial] learning notes
When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
Redis sentinel mechanism and configuration
Calculate the maximum path sum of binary tree
Adding database driver to sqoop of cdh6
Intel internal instructions - AVX and avx2 learning notes
ArrayList与LinkedList效率的对比
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
drools动态增加、修改、删除规则
What data types does redis have and their application scenarios
async/await 异步函数
drools中then部分的写法
Drools executes the specified rule
Docker-compose配置Mysql,Redis,MongoDB
[ybtoj advanced training guidance] cross the river [BFS]