1、DOM Manipulation using JavaScript| 使用 JavaScript 的 DOM
1、What can you use Client-side JavaScript for?
React to user input
对用户输入做出反应
Updating the page
更新页面
Validate form input values before being submitted to the server
在将表单输入值提交到服务器之前对其进行验证
Perform computations, sorting and animation
执行计算、排序和动画
Perform asynchronous Web API calls
执行异步 Web API 调用
2、Where to place JavaScript Code?
<script> tag in the head
<script src = "app.js"></script>
3、Role of JavaScript on the Client Side
DOM = A tree structure built out of the page HTML elements, where each HTML element is a node
DOM = 由页面 HTML 元素构建的树结构,其中每个 HTML 元素都是一个节点
Use JavaScript to manipulate the DOM
使用 JavaScript 作 DOM
4、Document Object Model (DOM) 文档对象模型
Object-oriented Representation of the document
文档的面向对象表示
DOM API consist of objects and methods to interact with the HTML page
DOM API 由与 HTML 页面交互的对象和方法组成
//html
<P>
Look at this girl:
<img src = "together.png" alt = "Firefly group photo" id = "icon01">
Beautiful.
</P>
<script src = "p1.js"></script>
//p1.js
const img = document.querySelector('#icon01')
img.src = 'firefly.png'
//网页会显示 firefly.png 这张图
5、Selecting Elements 选择元素
Access elements via their ID attribute
通过其 ID 属性访问元素
const element = document.getElementById("some-id")
Via the name attribute
通过 name 属性
const elArray = document.getElementsByName("some-name")
Via tag name
Via 标签名称
const imgTags = document.getElementsByTagName("img")
Returns array of <img> elements
返回<img>元素数组
用innerHTML进行页面展示
//html
<p id = "test1">Hello</p>
<p id = "test2"></p>
//p1.js
const a = document.getElementById("test1");//捕获id为test1的内容(Hello)并将其赋值给a
document.getElementById("test2").innerHTML = "id为test1的值是:" + a.innerHTML;
//页面显示
//Hello
//id为test1的值是:Hello
6、Selecting HTML Elements 选择 HTML 元素
Elements must be selected first before changing them or listening to their events
必须先选择元素,然后才能更改元素或侦听其事件
querySelector() returns the first element that matches a specified CSS selector in the document
querySelector() 返回与文档中的指定 CSS 选择器匹配的第一个元素
querySelectorAll() returns all elements in the document that matches a specified CSS selector
querySelectorAll() 返回文档中与指定 CSS 选择器匹配的所有元素
1. By tag name: document.querySelector("p")
2. By id : document.querySelector("#id")
3. By class: document.querySelector(".classname")
4. By attribute: document.querySelector("img[src='cat.png']")
返回 src 属性设置为 cat.png 的第一张图像
7、Common Element Properties|公共元素属性
value - get/set value of input elements 获取/设置输入元素的值
innerHTML - get/set the HTML content of an element 获取/设置元素的HTML内容
classList - the css classes of an element 元素的css类
8、Commonly used DOM methods|常用的 DOM 方法
添加元素
const newDiv = document.createElement('div')
newDiv.innerText = 'Div added by script'
document.body.append(newDiv)
//页面显示
//Div added by script
删除元素
document.querySelector('#myDiv').remove()
//删掉id为myDiv的元素
DOM 遍历
const parent = document.querySelector('#about').parentNode
const children = document.querySelector('#about').children
//我也不知道这逼玩意有啥用
隐藏和显示
//把id为myDiv的元素隐藏
document.querySelector('#myDiv').style.display = 'none'
//把id为myDiv的元素显示
document.querySelector('#myDiv').style.display = ''
添加/删除/引用 CSS 类
document.querySelector('#myDiv').classList.add('alert-success')
document.querySelector('#myDiv').classList.remove('alert-success')
document.querySelector('#myDiv').classList.toggle('alert-success')
9、data attributes 数据属性
data-* attributes allow us to store extra information on HTML elements
data-* 属性允许我们在 HTML 元素上存储额外的信息
The name of a custom data attribute begins with data-
自定义数据属性的名称以 data- 开头
10、Dataset property Dataset 属性
Dataset property is used to read write custom data attributes set on the element
Dataset 属性用于读取写入元素上设置的自定义数据属性
<div id="user"
data-id="123456"
data-user-name="johndoe">
John Doe
</div>
const el = document.querySelector('#user');
console.log(el.dataset);
//控制台会输出自定义数据属性
// set a data attribute
el.dataset.dob = '1960-10-03';
console.log("dob: ", el.dataset.dob);
delete el.dataset.dob;
console.log(el.dataset);
2、Event Handling|事件处理
1、Events Handling 事件处理
UI elements raise Events when the user interacts with them (such as a Clicked event is raised when a button is pressed)
UI 元素在用户与它们交互时引发事件(例如,当按下按钮时引发 Clicked 事件)
JavaScript can register event handlers to respond to UI events
JavaScript 可以注册事件处理程序来响应 UI 事件
Events are fired by the Browser and are sent to the specified JavaScript event handler function
事件由浏览器触发,并发送到指定的 JavaScript 事件处理程序函数
Can be set with HTML attributes (inline):
可以使用 HTML 属性(内联)进行设置:
<img src="test.gif" onclick="imageClicked()" />
Can be set through the DOM:
可以通过 DOM 设置:
const img = document.querySelector("#myImage")
img.addEventListener('click', imageClicked)
2、Event Handler Example 事件处理程序示例
//第一种方法
document.querySelector("#btnDate").addEventListener("click", displayDate)
function displayDate() {
document.querySelector("#date").innerHTML = Date()
}
//第二种方法
document.querySelector("#btnDate").addEventListener("click",function(){
document.querySelector("#date").innerHTML = Date()
})
//点击id为btnDate的元素,会在id为date的元素显示当前日期时间
3、Common DOM Events 常见 DOM 事件
鼠标事件:
onclick
:当用户点击(按下并松开)鼠标按钮时触发。
这是最常用的事件之一,例如点击按钮提交表单或触发弹窗。
onmousedown
:当用户按下鼠标按钮时触发,无需松开按钮即可触发。
可以用来检测点击开始的瞬间,比如实现拖拽功能。
onmouseup
:当用户松开鼠标按钮时触发。
通常与
onmousedown
配合使用来完成一组完整的操作。
onmouseover
:当鼠标悬停在某个元素上方时触发。
常用于显示提示信息或者改变元素样式。
onmouseout
:当鼠标离开某个元素的区域时触发。
通常用来还原样式或者隐藏提示信息。
onmousemove
:当鼠标在元素内移动时持续触发,即使没有按下鼠标按钮。
常用于跟踪鼠标位置,比如实现画板或拖拽效果。
主要活动:
onchange
:当表单中的元素(如输入框、下拉菜单)内容发生改变并失去焦点时触发。
通常用于监听用户输入的最终结果,例如动态验证用户填写的数据。
onkeypress
:当用户按下并保持键盘上的字符键时触发,但不包括功能键(如 Shift、Ctrl、Alt)。
已被逐渐淘汰,推荐使用
onkeydown
和onkeyup
代替。
onkeydown
:当用户按下任意键时触发,无需保持按住。
可以捕获所有键(包括功能键),通常用于检测用户输入开始的瞬间。
onkeyup
:当用户松开键盘上的任意键时触发。
通常用于检测输入完成后进行操作,比如实时搜索或验证输入内容。
接口事件:
onblur
:当一个元素(如输入框)失去焦点时触发。
通常用于在用户离开输入框后验证数据,例如检查输入是否符合要求。
onfocus
:当一个元素获得焦点时触发,例如用户点击或通过键盘导航到输入框时。
常用于高亮当前输入的元素或显示相关提示信息。
onscroll
:当用户滚动某个元素的内容(或整个页面)时触发。
通常用于实现动态加载、显示滚动位置或者触发动画效果。
表单事件:
onsubmit
:
当用户提交表单时触发,无论是通过点击提交按钮还是按 Enter 键。
处理表单提交前的验证(例如检查输入是否符合要求)。
阻止默认提交行为,通过调用
event.preventDefault()
,可以自定义提交逻辑。在服务器端或客户端执行操作(如保存数据或显示反馈信息)。
4、The Event Object 事件对象
function name (event) {
// an event handler function...
}
5、Stopping an Event 停止事件
preventDefault()stops the browser from doing its default action on an event.
3、HTML Template to generate the UI|用于生成 UI 的 HTML 模板
1、HTML template HTML 模板
HTML template has static parts and dynamic parts (the gaps to fill in)
HTML 模板有静态部分和动态部分(需要填补的空白)
const payment = {
date: '1/2/2021',
name: 'Mr Bean',
amount: 200,
reason: 'Donation',
receiver: 'Juha'
}
const receiptTemplate = (payment) =>
`<div>
<p>Date: ${payment.date}</p>
<p>Received from: ${payment.name}, the amount of QR ${payment.amount}</p>
<p>For: ${payment.reason}</p>
<p>Received by: ${payment.receiver}</p>
</div>`
console.log(receiptTemplate(payment));
// Render the template in the DOM
document.body.innerHTML = receiptTemplate(payment);
/*
网页输出
Date: 1/2/2021
Received from: Mr Bean, the amount of QR 200
For: Donation
Received by: Juha
/
2、Template Expressions 模板表达式
const a = 5, b = 10;
console.log(`${a} + ${b} = ${a + b}`);
//输出 5 + 10 = 15
注意这里的引号不是单引号和双引号,而是键盘上方一排数字左边的( ` ),如果用单引号( ‘ ’ )和双引号( “ ” ) ,输出就会变成${a} + ${b} = ${a + b}而不会替换对应模板
3、Display an Array using a Template literal 使用 Template 文本显示数组
Display an array elements using a template literal with the .map function
使用带有 .map 函数的模板文本显示数组元素
const days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"];
const daysHtml = `<ul>
${days.map(day => `<li>${day}</li>`).join('\n')}
</ul>`;
document.write(daysHtml);
/*
网页输出
·Mon
·Tue
·Wed
·Thurs
·Fri
·Sat
·Sun
/
4、Local Storage|本地储存
Local Storage provides mechanisms to store key/value pairs locally within the user's browser
Local Storage 提供了在用户浏览器中本地存储键/值对的机制
The storage limit is at least 5MB and information is never transferred to the server
存储限制至少为 5MB,并且信息永远不会传输到服务器
// Store存储
localStorage.lastname = "Saleh"
// Retrieve检索
console.log( localStorage.lastname )
// Delete删除
delete localStorage.lastname