Window对象与本地存储详解
一、Window对象
• BOM(浏览器对象模型)
• 定时器-延时函数
• JS执行机制
• location对象
• navigator对象
• histroy对象
• 目标:学习 window 对象的常见属性,知道各个 BOM 对象的功能含义
1.BOM
BOM(Browser Object Model ) 是浏览器对象模型
window对象是一个全局对象,也可以说是JavaScript中的顶级对象
像document、alert()、console.log()这些都是window的属性,基本BOM的属性和方法都是window的。
所有通过var定义在全局作用域中的变量、函数都会变成window对象的属性和方法
window对象下的属性和方法调用的时候可以省略window
<!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>
</head>
<body>
<script>
// document.querySelector()
// window.document.querySelector()
console.log(document === window.document)
function fn() {
console.log(11)
}
window.fn()
var num = 10
console.log(window.num)
</script>
</body>
</html>
2. 定时器-延时函数
两种定时器对比:
执行的次数
Ø 延时函数: 执行一次
Ø 间歇函数:每隔一段时间就执行一次,除非手动清除
⑴.案例:5秒钟之后消失的广告
<!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>
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>
</html>
3. JS执行机制
第一段代码
console.log(1111);
setTimeout(function () {
console.log(2222);
}, 1000);
console.log(3333);
JavaScript 是单线程执行的,并且拥有事件循环机制。同步任务会在主线程依次执行,异步任务(像setTimeout
)会被放入任务队列。
console.log(1111)
是同步任务,会马上执行,输出1111
。setTimeout
属于异步任务,它会等待 1000 毫秒(也就是 1 秒)之后,把回调函数放入任务队列。console.log(3333)
也是同步任务,会在setTimeout
之后马上执行,输出3333
。- 等主线程的同步任务执行完毕后,事件循环会去任务队列查看是否有任务需要执行。1 秒过后,
setTimeout
的回调函数被放入任务队列,此时主线程空闲,就会执行该回调函数,输出2222
。
所以,第一段代码的输出结果是:
1111
3333
2222
第二段代码
console.log(1111);
setTimeout(function () {
console.log(2222);
}, 0);
console.log(3333);
这段代码和第一段代码类似,不同之处在于setTimeout
的延迟时间设为了 0 毫秒。不过,即便延迟时间是 0 毫秒,setTimeout
的回调函数依然会被当作异步任务处理,不会立即执行,而是被放入任务队列等待。
console.log(1111)
是同步任务,会马上执行,输出1111
。setTimeout
虽然延迟时间为 0,但它的回调函数会被放入任务队列。console.log(3333)
是同步任务,会马上执行,输出3333
。- 主线程的同步任务执行完毕后,事件循环会去任务队列查看是否有任务需要执行,此时会执行
setTimeout
的回调函数,输出2222
。
所以,第二段代码的输出结果是:
1111
3333
2222
为了解决这个问题,利用多核 CPU 的计算能力,HTML5 提出 Web Worker 标准,允许 JavaScript 脚本创建多个 线程。于是,JS 中出现了同步和异步。
同步
前一个任务结束后再执行后一个任务,程序的执行顺序与任务的排列顺序是一致的、同步的。比如做饭的同 步做法:我们要烧水煮饭,等水开了(10分钟之后),再去切菜,炒菜。
异步
你在做一件事情时,因为这件事情会花费很长时间,在做这件事的同时,你还可以去处理其他事 情。比如做饭的异步做法,我们在烧水的同时,利用这10分钟,去切菜,炒菜。
他们的本质区别: 这条流水线上各个流程的执行顺序不同。
1. 先执行执行栈中的同步任务。
2. 异步任务放入任务队列中。
3. 一旦执行栈中的所有同步任务执行完毕,系统就会按次序读取任务队列中的异步任务,于是被读取的异步任务结束等待 状态,进入执行栈,开始执行。
由于主线程不断的重复获得任务、执行任务、再获取任务、再执行,所以这种机制被称为事件循环( event loop )。
代码执行步骤分析
console.log(1)
:这是一个同步任务,会立即执行,所以首先会在控制台输出1
。document.addEventListener('click', function () { console.log(4) })
:这行代码为document
对象添加了一个点击事件监听器。当document
被点击时,回调函数function () { console.log(4) }
才会被执行,它属于异步任务,不会影响后续代码的执行。console.log(2)
:这也是一个同步任务,会紧接着执行,在控制台输出2
。setTimeout(function () { }, 3000)
:setTimeout
是一个异步函数,它会在 3000 毫秒(即 3 秒)后将其回调函数放入任务队列。由于这里回调函数为空,所以不会有实际的输出操作,但它依然会按照异步机制处理。console.log(3)
:这是最后一个同步任务,会立即执行,在控制台输出3
。- 点击事件触发:当用户点击
document
时,之前添加的点击事件监听器的回调函数会被执行,在控制台输出4
。
输出结果总结
代码立即执行后,控制台会依次输出:
1
2
3
当用户点击 document
时,控制台会输出:
4
综上所述,代码立即执行的输出为 1
、2
、3
,之后若发生点击事件,还会输出 4
。
4. location对象
location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分
常用属性和方法:
Ø href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转
Ø search 属性获取地址中携带的参数,符号 ?后面部分
Ø hash 属性获取地址中的啥希值,符号 # 后面部分
Ø reload 方法用来刷新当前页面,传入参数 true 时表示强制刷新
常用属性和方法:
⑴href
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(window.location)
console.log(location)
console.log(location.href)
</script>
</body>
</html>
location.href = 'http://www.baidu.com' 这一条,啥都不点,会自动跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(window.location)
console.log(location)
console.log(location.href)
location.href = 'http://www.baidu.com'
</script>
</body>
</html>
案例:支付成功跳转回原网页
<!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>
span {
color: red;
}
</style>
</head>
<body>
<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)
</script>
</body>
</html>
⑵.search
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<form action="">
<input type="text" name="username">
<input type="password" name="pwd">
<button>提交</button>
</form>
<body>
<script>
console.log(location.search)
</script>
</body>
</html>
⑶hash
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<a href="#/my">我的</a>
<a href="#/friend">关注</a>
<a href="#/download">下载</a>
<body>
<script>
console.log(location.hash)
</script>
</body>
</html>
⑷reload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reload Example</title>
</head>
<body>
<h1>这是一个使用 reload 方法的示例页面</h1>
<button id="reloadButton">点击重新加载页面</button>
<script>
const reloadButton = document.getElementById('reloadButton');
reloadButton.addEventListener('click', function () {
// 使用 location.reload() 方法重新加载当前页面
location.reload();
});
</script>
</body>
</html>
5. navigator对象
navigator的数据类型是对象,该对象下记录了浏览器自身的相关信息
常用属性和方法:
Ø 通过 userAgent 检测浏览器的版本及平台
// 检测 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'
}
})()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Agent Detection</title>
</head>
<body>
<h1>正在检测您的设备类型...</h1>
<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';
}
})();
</script>
</body>
</html>
实际应用场景
在实际开发中,很多网站会为移动设备单独设计一套界面,也就是移动站点。移动站点的界面布局和交互方式通常会更适合在手机屏幕上使用,用户体验更佳。通过这段代码,网站能够自动识别用户的设备类型,若用户使用的是安卓或者 iPhone 设备,就会将其引导至移动站点,从而提升用户在移动设备上的浏览体验。
6. histroy对象
history 的数据类型是对象,主要管理历史记录, 该对象与浏览器地址栏的操作相对应,如前进、后退、历史记 录等
history 对象一般在实际开发中比较少用,但是会在一些 OA 办公系统中见到。
<!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>
</head>
<body>
<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>
</body>
</html>
二、本地存储
• 本地存储介绍
• 本地存储分类
• 存储复杂数据类型
• 目标:学习 window 对象的常见属性,知道各个 BOM 对象的功能含义
1 本地存储介绍
以前我们页面写的数据一刷新页面就没有了,是不是?
随着互联网的快速发展,基于网页的应用越来越普遍,同时也变的越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据,HTML5规范提出了相关解决方案。
1、数据存储在用户浏览器中
2、设置、读取方便、甚至页面刷新不丢失数据
3、容量较大,sessionStorage和localStorage约 5M 左右
常见的使用场景:
https://todomvc.com/examples/vanilla-es6/ 页面刷新数据不丢失
2.本地存储分类- localStorage
目标: 能够使用localStorage 把数据存储的浏览器中
作用: 可以将数据永久存储在本地(用户的电脑), 除非手动删除,否则关闭页面也会存在
特性:
Ø 可以多窗口(页面)共享(同一浏览器可以共享)
Ø 以键值对的形式存储使用
浏览器查看本地数据:
<!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>
</head>
<body>
<script>
// 1. 要存储一个名字 'uname', 'pink老师'
// localStorage.setItem('键','值')
localStorage.setItem('uname', '老师')
// 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'))
</script>
</body>
</html>
特性:
3. 存储复杂数据类型
解决:需要将复杂数据类型转换成JSON字符串,在存储到本地
问题:因为本地存储里面取出来的是字符串,不是对象,无法直接使用
<!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>
</head>
<body>
<script>
const obj = {
uname: '老师',
age: 18,
gender: '女'
}
// // 存储 复杂数据类型 无法直接使用
// localStorage.setItem('obj', obj) [object object]
// // 取
// console.log(localStorage.getItem('obj'))
// 1.复杂数据类型存储必须转换为 JSON字符串存储
localStorage.setItem('obj', JSON.stringify(obj))
// JSON 对象 属性和值有引号,而是引号统一是双引号
// {"uname":"pink老师","age":18,"gender":"女"}
// 取
// console.log(typeof localStorage.getItem('obj'))
// 2. 把JSON字符串转换为 对象
const str = localStorage.getItem('obj') // {"uname":"老师","age":18,"gender":"女"}
console.log(JSON.parse(str))
</script>
</body>
</html>
三、综合案例
1.案例:学生就业信息表
css
* {
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, .info select {
width: 80px;
height: 27px;
outline: none;
border-radius: 5px;
border:1px solid #b8daff;
padding-left: 5px;
box-sizing: border-box;
margin-right: 15px;
}
.info button {
width: 60px;
height: 27px;
background-color: #004085;
outline: none;
border: 0;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
.info .age {
width: 50px;
}
html
<!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="css/index.css" />
</head>
<body>
<h1>新增学员</h1>
<form class="info" autocomplete="off">
姓名:<input type="text" class="uname" name="uname" />
年龄:<input type="text" class="age" name="age" />
性别:
<select name="gender" class="gender">
<option value="男">男</option>
<option value="女">女</option>
</select>
薪资:<input type="text" class="salary" name="salary" />
就业城市:<select name="city" class="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
<option value="曹县">曹县</option>
</select>
<button class="add">录入</button>
</form>
<h1>就业榜</h1>
<table>
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>薪资</th>
<th>就业城市</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!--
<tr>
<td>1001</td>
<td>欧阳霸天</td>
<td>19</td>
<td>男</td>
<td>15000</td>
<td>上海</td>
<td>
<a href="javascript:">删除</a>
</td>
</tr>
-->
</tbody>
</table>
<script>
// 参考数据
// const initData = [
// {
// stuId: 1001,
// uname: '欧阳霸天',
// age: 19,
// gender: '男',
// salary: '20000',
// city: '上海',
// }
// ]
// 1. 读取本地存储的数据 student-data 本地存储的命名
const data = localStorage.getItem('student-data')
// console.log(data)
// 2. 如果有就返回对象,没有就声明一个空的数组 arr 一会渲染的时候用的
const arr = data ? JSON.parse(data) : []
// console.log(arr)
// 获取 tbody
const tbody = document.querySelector('tbody')
// 3. 渲染模块函数
function render() {
// 遍历数组 arr,有几个对象就生成几个 tr,然后追击给tbody
// map 返回的是个数组 [tr, tr]
const trArr = arr.map(function (item, i) {
// console.log(item)
// console.log(item.uname) // 欧阳霸天
return `
<tr>
<td>${item.stuId}</td>
<td>${item.uname}</td>
<td>${item.age}</td>
<td>${item.gender}</td>
<td>${item.salary}</td>
<td>${item.city}</td>
<td>
<a href="javascript:" data-id=${i}>删除</a>
</td>
</tr>
`
})
// console.log(trArr)
// 追加给tbody
// 因为 trArr 是个数组, 我们不要数组,我们要的是 tr的字符串 join()
tbody.innerHTML = trArr.join('')
}
render()
// 4. 录入模块
const info = document.querySelector('.info')
// 获取表单form 里面带有 name属性的元素
const items = info.querySelectorAll('[name]')
// console.log(items)
info.addEventListener('submit', function (e) {
// 阻止提交
e.preventDefault()
// 声明空的对象
const obj = {}
// obj.stuId = arr.length + 1
// 加入有2条数据 2
obj.stuId = arr.length ? arr[arr.length - 1].stuId + 1 : 1
// 非空判断
for (let i = 0; i < items.length; i++) {
// console.log(items) // 数组里面包含 5个表单 name
// console.log(items[i]) // 每一个表单 对象
// console.log(items[i].name) //
// item 是每一个表单
const item = items[i]
if (items[i].value === '') {
return alert('输入内容不能为空')
}
// console.log(item.name) uname age gender
// obj[item.name] === obj.uname obj.age
obj[item.name] = item.value
}
// console.log(obj)
// 追加给数组
arr.push(obj)
// 把数组 arr 存储到本地存储里面
localStorage.setItem('student-data', JSON.stringify(arr))
// 渲染页面
render()
// 重置表单
this.reset()
})
// 5. 删除模块
tbody.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
// alert(1)
// console.log(e.target.dataset.id)
// 删除数组对应的这个数据
arr.splice(e.target.dataset.id, 1)
// 写入本地存储
localStorage.setItem('student-data', JSON.stringify(arr))
// 重新渲染
render()
}
})
</script>
</body>
</html>
四、数组中map方法 迭代数组
作用:map 迭代数组
语法:
使用场景:map 可以处理数据,并且返回新的数组
<!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>
</head>
<body>
<script>
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)
</script>
</body>
</html>
五、数组中join方法
作用:join() 方法用于把数组中的所有元素转换一个字符串
语法:
参数:
数组元素是通过参数里面指定的分隔符进行分隔的
<!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>
</head>
<body>
<script>
const arr = ['red', 'blue', 'green']
// 把数组元素转换为字符串
console.log(arr.join('*'))
</script>
</body>
</html>