目录
一、Window对象
1、BOM(浏览器对象模型)
2、定时器-延时函数
3、 JS执行机制
(1)同步任务:
(2)异步任务:
4、location对象
(1)5秒钟后跳转页面
6、history对象
二、本地存储
1、介绍
2、分类(localStorage)
3、存储复杂数据类型
三、数组中一些方法
1、map方法
2、join方法
四、学生就业统计表案例
1、业务逻辑:
2、实现的效果图:
3、核心代码如下:
一、Window对象
1、BOM(浏览器对象模型)
- window对象是一个全局对象,也可以说是JavaScript中的顶级对象
- 像document、alert()、console.log()这些都是window的属性,基本BOM的属性和方法都是window的。
- 所有通过var定义在全局作用域中的变量、函数都会变成window对象的属性和方法
- window对象下的属性和方法调用的时候可以省略window
2、定时器-延时函数
- JavaScript 内置的一个用来让代码延迟执行的函数,叫 setTimeout
- 语法:
- setTimeout(回调函数,等待的毫秒数)
- setTimeout 仅仅只执行一次,所以可以理解为就是把一段代码延迟执行, 平时省略window
- 清除延时函数:
- let timer =setTimeout(回调函数,等待的毫秒数)
- clearTimeout(timer)
- 注意点:延时器需要等待,所以后面的代码先执行。每一次调用延时器都会产生一个新的延时器
示例代码如下:
<script>
setTimeout(function () {
console.log('时间到了')
}, 2000)
</script>
案例:5秒钟后消失的广告
示例代码如下:
<style>
img {
position: fixed;
left: 0;
bottom: 0;
}
</style>
</head>
<body>
<img src="./images/ad.png" alt="">
<script>
// 1.获取元素
const img = document.querySelector('img')
setTimeout(function () {
img.style.display = 'none'
}, 3000)
</script>
</body>
3、 JS执行机制
- 为了解决这个问题,利用多核 CPU 的计算能力,HTML5 提出 Web Worker 标准,允许 JavaScript 脚本创建多个 线程。于是,JS 中出现了同步和异步。
- 同步:前一个任务结束后再执行后一个任务,程序的执行顺序与任务的排列顺序是一致的、同步的。比如做饭的同 步做法:我们要烧水煮饭,等水开了(10分钟之后),再去切菜,炒菜。
- 异步:你在做一件事情时,因为这件事情会花费很长时间,在做这件事的同时,你还可以去处理其他事 情。比如做饭的异步做法,我们在烧水的同时,利用这10分钟,去切菜,炒菜。
- 他们的本质区别: 这条流水线上各个流程的执行顺序不同
(1)同步任务:
同步任务都在主线程上执行,形成一个执行栈。
(2)异步任务:
JS 的异步是通过回调函数实现的。
一般而言,异步任务有以下三种类型:
1、普通事件,如 click、resize 等
2、资源加载,如 load、error 等
3、定时器,包括 setInterval、setTimeout 等 异步任务相关添加到任务队列中(任务队列也称为消息队列)
4、执行过程
先执行执行栈里面的同步任务,异步任务放到任务队列中,一旦执行栈中的所有的同步任务执行完之后,系统会依次读取任务队列里的异步任务,读取完异步任务后,然后进入执行栈,开始执行。
由于主线程不断的重复获得任务、执行任务、再获取任务、再执行,所以这种机制被称为事件循环( event loop )
4、location对象
- location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分
- 常用属性和方法:
- href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转
- search 属性获取地址中携带的参数,符号 ?后面部分
- hash 属性获取地址中的啥希值,符号 # 后面部分
- reload 方法用来刷新当前页面,传入参数 true
- location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分
- 常用属性和方法:
- href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转
示例代码如下:
console.log(location.href)
// 1. href 经常用href 利用js的方法去跳转页面
location.href = 'http://www.baidu.com'
<body>
<form action="">
<input type="text" name="username">
<input type="password" name="pwd">
<button>提交</button>
</form>
<a href="#/my">我的</a>
<a href="#/friend">关注</a>
<a href="#/download">下载</a>
<button class="reload">刷新</button>
<script>
// console.log(window.location)
// console.log(location)
console.log(location.href)
// 1. href 经常用href 利用js的方法去跳转页面
location.href = 'http://www.baidu.com'
const reload = document.querySelector('.reload')
reload.addEventListener('click', function () {
// f5 刷新页面
// location.reload()
// 强制刷新 ctrl+f5
location.reload(true)
})
</script>
</body>
(1)5秒钟后跳转页面
需求:用户点击可以跳转,如果不点击,则5秒之后自动跳转,要求里面有秒数倒计时
示例代码如下:
<a href="http://www.itcast.cn">支付成功<span>5</span>秒钟之后跳转到首页</a>
<script>
// 1. 获取元素
const a = document.querySelector('a')
// 2.开启定时器
// 3. 声明倒计时变量
let num = 5
let timerId = setInterval(function () {
num--
a.innerHTML = `支付成功<span>${num}</span>秒钟之后跳转到首页`
// 如果num === 0 则停止定时器,并且完成跳转功能
if (num === 0) {
clearInterval(timerId)
// 4. 跳转 location.href
location.href = 'http://www.itcast.cn'
}
}, 1000)
- location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分
- 常用属性和方法:
- search 属性获取地址中携带的参数,符号 ?后面部分
5、navigator对象
- navigator的数据类型是对象,该对象下记录了浏览器自身的相关信息
- 常用属性和方法:
- 通过 userAgent 检测浏览器的版本及平台
示例代码如下:
<script>
// 检测 userAgent(浏览器信息)
!(function () {
const userAgent = navigator.userAgent
// 验证是否为Android或iPhone
const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
// 如果是Android或iPhone,则跳转至移动站点
if (android || iphone) {
location.href = 'http://m.itcast.cn'
}
})();
// !(function () { })();
!function () { }()
</script>
6、history对象
history 的数据类型是对象,主要管理历史记录, 该对象与浏览器地址栏的操作相对应,如前进、后退、历史记录等
常用的方法和属性:
示例代码如下:
<button>后退</button>
<button>前进</button>
<script>
const back = document.querySelector('button:first-child')
const forward = back.nextElementSibling
back.addEventListener('click', function () {
// 后退一步
// history.back()
history.go(-1)
})
forward.addEventListener('click', function () {
// 前进一步
// history.forward()
history.go(1)
})
</script>
二、本地存储
1、介绍
- 随着互联网的快速发展,基于网页的应用越来越普遍,同时也变的越来越复杂,为了满足各种各样的需求,会经常 性在本地存储大量的数据,HTML5规范提出了相关解决方案。
- 1、数据存储在用户浏览器中
- 2、设置、读取方便、甚至页面刷新不丢失数据
- 3、容量较大,sessionStorage和localStorage约 5M 左
2、分类(localStorage)
- 作用:可以将数据永久存储在本地(用户的电脑), 除非手动删除,否则关闭页面也会存在
- 特性: 可以多窗口(页面)共享(同一浏览器可以共享),以键值对的形式存储使用
- 语法:
示例代码如下:
// 1. 要存储一个名字 'uname', 'pink老师'
// localStorage.setItem('键','值')
localStorage.setItem('uname', 'pink老师')
// 2. 获取方式 都加引号
console.log(localStorage.getItem('uname'))
// 3. 删除本地存储 只删除名字
// localStorage.removeItem('uname')
// 4. 改 如果原来有这个键,则是改,如果么有这个键是增
localStorage.setItem('uname', 'red老师')
// 我要存一个年龄
// 2. 本地存储只能存储字符串数据类型
localStorage.setItem('age', 18)
console.log(localStorage.getItem('age'))
- 浏览器查看本地数据:
分类- sessionStorage
- 特性:
- 生命周期为关闭浏览器窗口
- 在同一个窗口(页面)下数据可以共享
- 以键值对的形式存储使用
- 用法跟localStorage 基本相同
3、存储复杂数据类型
- 本地只能存储字符串,无法存储复杂数据类型
const obj = {
uname: 'pink',
age: 18,
gender: '男'
}
localStorage.setItem('obj',obj)
- 解决:需要将复杂数据类型转换成JSON字符串,在存储到本地
- 语法:JSON.stringify(复杂数据类型)
const obj = {
uname: 'pink',
age: 18,
gender: '男'
}
localStorage.setItem('obj',JSON.stringify(obj))
- 问题:因为本地存储里面取出来的是字符串,不是对象,无法直接使用
const obj = localStorage.getItem('obj')
console.log(obj)
- 解决:把取出来的字符串转换为对象
- 语法:JSON.parse(JSON字符串)
const obj = JSON.parse(localStorage.getItem('obj'))
console.log(obj);
- 将JSON字符串转换成对象 取出 时候使用
三、数组中一些方法
1、map方法
- 作用:map 迭代数组
- 语法:
示例代码如下:
const arr = ['red', 'blue', 'green']
// map 方法也是遍历 处理数据 可以返回一个数组
const newArr = arr.map(function (item, i) {
// console.log(item) // 数组元素 'red'
// console.log(i) // 下标
return item + '老师'
})
console.log(newArr)
['red老师', 'blue老师', 'green老师']
const arr1 = [10, 20, 30]
const newArr1 = arr1.map(function (item) {
return item + 10
})
console.log(newArr1)
- 使用场景: map 可以处理数据,并且返回新的数组
- map 也称为映射。映射是个术语,指两个元素的集之间元素相互“对应”的关系
2、join方法
- 作用: join() 方法用于把数组中的所有元素转换一个字符串
- 语法:
示例代码如下:
const arr = ['red', 'blue', 'green']
// 把数组元素转换为字符串
console.log(arr.join(''))
console.log(arr.join('-'))
console.log(arr.join('*'))
- 参数: 数组元素是通过参数里面指定的分隔符进行分隔的
四、学生就业统计表案例
1、业务逻辑:
2、实现的效果图:
3、核心代码如下:
(1)CSS样式代码如下:
* {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
color: #721c24;
}
h1 {
text-align: center;
color: #333;
margin: 20px 0;
}
.title {
width: 933px;
height: 50px;
line-height: 50px;
padding-right: 15px;
border: 1px solid #ebebeb;
margin: 10px auto;
background-color: #f2f2f2;
text-align: right;
}
.title span {
display: inline-block;
vertical-align: middle;
height: 20px;
margin: -3px 5px 0;
text-align: center;
line-height: 20px;
color: #f26934;
font-weight: 700;
}
table {
margin: 0 auto;
width: 950px;
border-collapse: collapse;
color: #3c3637;
}
th {
padding: 10px;
background: #f2f2f2;
font-size: 18px;
text-align: left;
}
td,
th {
border: 1px solid #ebebeb;
padding: 15px;
}
td {
color: #666;
font-size: 16px;
}
tbody tr {
background: #fff;
}
tbody tr:hover {
background: #fbfafa;
}
tbody a {
display: inline-block;
width: 80px;
height: 30px;
text-align: center;
line-height: 30px;
color: #fff;
background-color: #f26934;
}
.info {
width: 900px;
margin: 50px auto;
text-align: center;
}
.info input,
.info select {
width: 100px;
height: 30px;
outline: none;
border: 1px solid #ebebeb;
padding-left: 5px;
box-sizing: border-box;
margin-right: 10px;
}
.info button {
width: 70px;
height: 30px;
background-color: #5dbfd8;
outline: none;
border: 0;
color: #fff;
cursor: pointer;
font-size: 14px;
}
.info button:hover {
background-color: #52abc1;
}
(2)字体图标样式代码如下:
@font-face {
font-family: "iconfont"; /* Project id 3873122 */
src: url('iconfont.woff2?t=1675070457031') format('woff2'),
url('iconfont.woff?t=1675070457031') format('woff'),
url('iconfont.ttf?t=1675070457031') format('truetype');
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-shanchu:before {
content: "\e718";
}
.icon-tianjia:before {
content: "\e6de";
}
(3)index代码如下:(含JavaScript代码)
<!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>学生就业统计表</title>
<link rel="stylesheet" href="./iconfont/iconfont.css">
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<h1>学生就业统计表</h1>
<form class="info" autocomplete="off">
<input type="text" class="uname" name="uname" placeholder="姓名" />
<input type="text" class="age" name="age" placeholder="年龄" />
<input type="text" class="salary" name="salary" placeholder="薪资" />
<select name="gender" class="gender">
<option value="男">男</option>
<option value="女">女</option>
</select>
<select name="city" class="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
<option value="曹县">曹县</option>
</select>
<button class="add">
<i class="iconfont icon-tianjia"></i>添加
</button>
</form>
<div class="title">共有数据<span>0</span>条</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>薪资</th>
<th>就业城市</th>
<th>录入时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- <tr>
<td>1</td>
<td>迪丽热巴</td>
<td>23</td>
<td>女</td>
<td>12000</td>
<td>北京</td>
<td>2099/9/9 08:08:08</td>
<td>
<a href="javascript:">
<i class="iconfont icon-shanchu"></i>
删除
</a>
</td>
</tr> -->
</tbody>
</table>
<script>
// 参考数据
const initData = [
{
stuId: 1,
uname: '迪丽热巴',
age: 22,
salary: '12000',
gender: '女',
city: '北京',
time: '2099/9/9 08:08:08'
}
]
// localStorage.setItem('data', JSON.stringify(initData))
// 1.渲染业务
// 1.1先读取本地存储的数据
// (1).本地存储有数据则记得转换为对象然后存储到变量里面,后期用于渲染页面
///(2).如果没有数据,则用空数组来代替
const arr = JSON.parse(localStorage.getItem('data')) || []
console.log(arr);
//1.2利用map和join方法来渲染页面
const tbody = document.querySelector('tbody')
function render() {
//(1).利用map遍历数组,返回对应的tr的数组
const trArr = arr.map(function (ele, index) {
return `
<tr>
<td>${ele.stuId}</td>
<td>${ele.uname}</td>
<td>${ele.age}</td>
<td>${ele.gender}</td>
<td>${ele.salary}</td>
<td>${ele.city}</td>
<td>${ele.time}</td>
<td>
<a href="javascript:" data-id="${index}">
<i class="iconfont icon-shanchu"></i>
删除
</a>
</td>
</tr>
`
})
console.log(trArr);
//(2).把数组转换为字符串join
//(3).把生成的字符市追加给tbody
tbody.innerHTML = trArr.join('')
//显示共计有几条数据
document.querySelector('.title span').innerHTML = arr.length
}
render()
//2.新增业务
// 2.1 form表单注册提交事件,阻止默认行为
const info = document.querySelector('.info')
const uname = document.querySelector('.uname')
const age = document.querySelector('.age')
const salary = document.querySelector('.salary')
const gender = document.querySelector('.gender')
const city = document.querySelector('.city')
info.addEventListener('submit', function (e) {
e.preventDefault()
//2.2非空判断
if (!uname.value || !age.value || !salary.value) {
return alert('输入的内容不能为空')
}
//2.3给arr数组追加对象,里面存储表单获取过来的数据
//处理stuId:数组最后一条数据的stuId + 1
arr.push({
stuId: arr.length ? arr[arr.length - 1].stuId + 1 : 1,
uname: uname.value,
age: age.value,
salary: salary.value,
gender: gender.value,
city: city.value,
time: new Date().toLocaleString()
})
// 2.4 渲染页面和重置表单(reset()方法)
render()
this.reset()//重置表单 this是info
// 2.5把数组重新存入本地存储里面,记得转换为JSON字符串存储
localStorage.setItem('data', JSON.stringify(arr))
})
//3.删除业务
// 3.1采用事件委托形式,给 tbody 注册点击事件
tbody.addEventListener('click', function (e) {
//判断是否点击的是删除按钮 A链接
if (e.target.tagName === 'A') {
// alert(11)
//3.2得到当前点击链接的索引号。渲染数据的时候,动态给a链接添加自定义属性例如 data-id="0"
console.log(e.target.dataset.id);
//确认是否真的要删除
if (confirm('您确定要删除这条数据吗?')) {
// 3.3根据索引号,利用splice 删除数组这条数据
arr.splice(e.target.dataset.id, 1)
//3.4重新渲染页面
render()
//3.5把最新arr数组存入本地存储
localStorage.setItem('data', JSON.stringify(arr))
}
}
})
</script>
</body>
</html>