storage 事件在对localStorage与sessionStorage进行数据进行增删改操作时触发。
此事件对于两种本地存储方式都有效,下面仅以localStorage做一下介绍。
关于事件处理函数注册,可以参阅如何注册事件处理函数一章节。
关于上述两种数据本地存储方案概述参阅如下两篇文章:
(1).localStorage 用法一章节。
(2).sessionStorage 用法一章节。
下面通过代码实例对此事件进行一下详细介绍。
[HTML] 纯文本查看 复制代码运行代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title></title>
<style>
div{
width:200px;
height:50px;
color:red;
margin:0px auto;
}
</style>
<script>
localStorage.setItem("name","");
localStorage.setItem("address","青岛市南区");
localStorage.setItem("url","www.softwhy.com");
</script>
</head>
<body>
<div>在谷歌开发者工具查看效果</div>
</body>
</html>
上述代码会在localStorage中添加三条数据,谷歌开发者工具截图如下:
a:3:{s:3:\"pic\";s:43:\"portal/201910/23/145442kzyhmb982g3m06z3.png\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}
下面为storage 事件注册事件处理函数监听对localStorage的操作。
[HTML] 纯文本查看 复制代码运行代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title></title>
<style>
div{
width:200px;
height:50px;
color:red;
margin:0px auto;
}
</style>
<script>
window.onload = () =>{
let obt=document.getElementById("bt");
let odiv=document.getElementById("ant");
// storage 事件处理函数
addEventListener('storage',function(e){
odiv.innerHTML="";
},false)
// click 事件处理函数
obt.addEventListener('click',function(e){
localStorage.setItem("age",5);
},false)
}
</script>
</head>
<body>
<div id="ant"></div>
<input type="button" value="查看效果" id="bt"/>
</body>
</html>
预期效果是,点击按钮添加一条数据项,触发事件,将相应字符串写入div。
但是代码并未达到预期目的,分析如下:
(1).点击按钮通过setItem()方法新增一条数据,于是触发storage 事件。
(2).但是实际运行效果却是,事件处理函数并未执行。
(3).因为在A页面对本地存储的数据操作事件,需要在同源的其他页面监听。
此事件的事件对象具有如下几个属性:
事件对象属性:
(1).key:字符串类型,被修改、删除或者添加的键名。
(2).oldValue:任意类型,被重写或者添加之前的value值。
(3).newValue:任意类型,被重写或者修改的新值。
(4).url/uri:字符串类型,触发事件的页面地址。
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56323.shtml