当前位置:网站首页>JS本地存储 sessionStorage和localStorage

JS本地存储 sessionStorage和localStorage

2022-08-09 12:59:00 _七七

sessionStorage

<!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>Document</title>
</head>

<body>
    <input type="text">
    <button class="set">存储数据</button>
    <button class="get">获取数据</button>
    <button class="remove">删除数据</button>
    <button class="del">清空所有数据</button>
    <script> // 关闭浏览器失效 console.log(localStorage.getItem('username')); var ipt = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove = document.querySelector('.remove'); var del = document.querySelector('.del'); set.addEventListener('click', function () {
       // 当我们点击了之后,就可以把表单里面的值存储起来 var val = ipt.value; sessionStorage.setItem('uname', val); sessionStorage.setItem('pwd', val); }); get.addEventListener('click', function () {
       // 当我们点击了之后,就可以把表单里面的值获取过来 console.log(sessionStorage.getItem('uname')); }); remove.addEventListener('click', function () {
       //  sessionStorage.removeItem('uname'); }); del.addEventListener('click', function () {
       // 当我们点击了之后,清除所有的 sessionStorage.clear(); }); </script>
</body>

</html>

localStorage

<!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>Document</title>
</head>

<body>
    <input type="text">
    <button class="set">存储数据</button>
    <button class="get">获取数据</button>
    <button class="remove">删除数据</button>
    <button class="del">清空所有数据</button>
    <script> // 永久生效 var ipt = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove = document.querySelector('.remove'); var del = document.querySelector('.del'); set.addEventListener('click', function () {
       var val = ipt.value; localStorage.setItem('username', val); }) get.addEventListener('click', function () {
       console.log(localStorage.getItem('username')); }) remove.addEventListener('click', function () {
       localStorage.removeItem('username'); }) del.addEventListener('click', function () {
       localStorage.clear(); }) </script>
</body>

</html>
原网站

版权声明
本文为[_七七]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_43472877/article/details/126158152