localStorage 实现了本地的永久存储;
这一点和sessionStorage不同,后者在会话结束就清除了;
先来看看localStorage的添加,应该是设置,“添加”不准确;
方法:setItem( );
实例:
<!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>localstorage</title>
</head>
<body>
<script>
localStorage.setItem("cvper","skate and music!");
</script>
</body>
</html>
然后执行这个网页文件,再打开控制台查看:我们可以看到数据已经存储进去,而且是永久存储
下面看看如何获取已经存储的数据:
方法: getItem( )
实例:在上面设置的基础上修改一下
<!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>localstorage</title>
</head>
<body>
<script>
console.log(localStorage.getItem("cvper"))
</script>
</body>
</html>
控制台输出 :skate and music!
再来看看如何删除设置的数据:
方法:removeItem( )
实例:在上面的基础上修改
<!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>localstorage</title>
</head>
<body>
<script>
localStorage.removeItem("cvper");
</script>
</body>
</html>
再去查看localstorage 里面已经没有信息了;
最后一个方法:清除 clear( ) 使用: localstoage.clear(); 请自行尝试吧。。。