当前位置:网站首页>Web APIs DOM event delegation + comprehensive case
Web APIs DOM event delegation + comprehensive case
2022-07-21 00:48:00 【Dark horse programmer official】
Notes updated in the early stage : Web API Basic cognition / obtain DOM Elements / Set up / modify DOM Element content and element attributes / Timer - Intermittent function / The basis of the event / Higher order function / Environment object / Comprehensive case -Tab Bar Toggle / DOM node /DOM Time object /DOM Redraw and reflow / DOM- Event object /DOM- Flow of events
The goal is : Be able to say the benefits of event delegation
One 、 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
Event delegation code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<ul>
<li> I am the first 1 Small li</li>
<li> I am the first 2 Small li</li>
<li> I am the first 3 Small li</li>
<li> I am the first 4 Small li</li>
<li> I am the first 5 Small li</li>
</ul>
<script>
// Don't every little li Registered event Instead, he entrusted the incident to his father
// Event delegation is to add events to the parent Instead of children adding events
let ul = document.querySelector('ul')
ul.addEventListener('click', function (e) {
// alert(' I clicked ')
// Get the current element
// console.log(e.target)
e.target.style.color = 'red'
})
</script>
</body>
</html>
Two 、 Case study 1: Render student information cases
demand : Click the enter button , Can add student information
explain :
The main purpose of this case is to learn later Vue Do matting ( Data-driven view )
demand ①: Add data
- Click the enter button , Put all the values in the form into the array
- Automatic generation of student number , Is the student number of the last data in the array +1
demand ②: Rendering
- Render the data of the array to the page , At the same time, clear the values in the form , The values of the drop-down list are restored
- Be careful , Before rendering , Empty the previously rendered content first
- Because multiple renderings , It's best to encapsulate it as a function
demand ③: Delete data
- To improve performance , It's best to use event delegation , Click to find the link e.target.tagName
- Delete link according to current , Find this data
- I can use it when I need it findIndex Method to find the index number of the array element for easy deletion
- And then use splice To delete the corresponding data
- To render
CSS Code :
* {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
color:#721c24;
}
h1 {
text-align: center;
color:#333;
margin: 20px 0;
}
table {
margin:0 auto;
width: 800px;
border-collapse: collapse;
color:#004085;
}
th {
padding: 10px;
background: #cfe5ff;
font-size: 20px;
font-weight: 400;
}
td,th {
border:1px solid #b8daff;
}
td {
padding:10px;
color:#666;
text-align: center;
font-size: 16px;
}
tbody tr {
background: #fff;
}
tbody tr:hover {
background: #e1ecf8;
}
.info {
width: 900px;
margin: 50px auto;
text-align: center;
}
.info input {
width: 80px;
height: 25px;
outline: none;
border-radius: 5px;
border:1px solid #b8daff;
padding-left: 5px;
}
.info button {
width: 60px;
height: 25px;
background-color: #004085;
outline: none;
border: 0;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
.info .age {
width: 50px;
}
user Templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/user.css">
</head>
<body>
<h1> New students </h1>
<div class="info">
full name :<input type="text" class="uname">
Age :<input type="text" class="age">
Gender : <select name="gender" id="" class="gender">
<option value=" male "> male </option>
<option value=" Woman "> Woman </option>
</select>
Salary :<input type="text" class="salary">
Employment city :<select name="city" id="" class="city">
<option value=" Beijing "> Beijing </option>
<option value=" Shanghai "> Shanghai </option>
<option value=" Guangzhou "> Guangzhou </option>
<option value=" Shenzhen "> Shenzhen </option>
<option value=" Cao County "> Cao County </option>
</select>
<button class="add"> entry </button>
</div>
<h1> Employment list </h1>
<table>
<thead>
<tr>
<th> Student number </th>
<th> full name </th>
<th> Age </th>
<th> Gender </th>
<th> Salary </th>
<th> Employment city </th>
<th> operation </th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1001</td>
<td> Ouyang batian </td>
<td>19</td>
<td> male </td>
<td>15000</td>
<td> Shanghai </td>
<td>
<a href="javascript:"> Delete </a>
</td>
</tr> -->
</tbody>
</table>
<script>
// 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
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)
// I want to get a Of id need
// console.log(e.target.id)
arr.splice(e.target.id, 1)
// Re render our function
render()
}
})
</script>
</body>
</html>
Dark horse front-end column has a lot of dry goods , Focus on relearning , It's convenient ~
2022 Front end learning roadmap : Course 、 Source code 、 note , Technology stack In addition, the circuit diagram is updated in real time ! Friends who need after-school materials , You can tell me directly .
边栏推荐
- STM32移植LVGL8.2
- CCTV news "Guangzhou rent quota invoice by hand" news channel_ People's network
- Learun, open source, one Net web quick open
- 央视新闻《宁波开餐饮手撕定额发票》新闻频道_人民网
- CCTV news "Jinan rent quota invoice by hand" news channel_ People's network
- 【JVM 系列】JVM 中常见的垃圾回收器
- 如何入门.NET Core ? 推荐这10个优秀的开源项目!
- 央视新闻《广州开餐饮手撕定额发票》新闻频道_人民网
- weex排雷1:data this
- typeof与keyof
猜你喜欢
10. Démarrage rapide du moteur
软件测试知识库+1,5款顶级自动化测试工具推荐和使用分析
Deeply participated in opengauss Developer Day 2022, cloud and enmo showed their style in a number of activities
Openvino model learning - from model to pipeline production
C # understand these 100 + lines of code, and you will really get started (Classic)
QT_ code
EasyCVR平台针对360浏览器自动填充密码问题的解决办法
Why has API strategy become a magic weapon for enterprises' digital transformation?
推荐一个开源商城
10、gin快速入门
随机推荐
怎么使用mySQL语句导出表
Common interview questions for app UI automated testing may be useful~
How can easycvr solve RTMP offline caused by restarting after configuring RTMP streaming?
如何查看Win11可以升级22h2?Win11升级22h2的方法
MYSQL中变量的操作
央视新闻《苏州开餐饮手撕定额发票》新闻频道_人民网
Recommend an open source mall
Ansible introduction and installation
开发者必读:2022年移动应用运营增长洞察白皮书
APP UI自动化测试常见面试题,或许有用呢~
Win11新Bug任务栏图标不显示的解决方法
How to get started NET Core ? Recommend these 10 excellent open source projects!
Protocol buffer learning
CCTV news "Shenzhen rent quota invoice by hand" news channel_ People's network
央视新闻《宁波开餐饮手撕定额发票》新闻频道_人民网
codeforces每日5题(均1500)-第二十天
推荐一个开源商城
How to get asp Net core current startup address?
Learun,已开源,一个.net web快速开
央视新闻《天津开餐饮手撕定额发票》新闻频道_人民网