前端localStorage使用

何为localStorage?
  • 在html5中,新增了localStorage和sessionStorage来实现本地存储,它们统称为web Storage.目的是为了解决cookie存储空间不足的问题.这里笔者只提及localStorage的使用
localStorage的优势和不足
优势
  • 存储空间的扩大(一般为5M)
  • 没有时间限制,若不手动删除的话可以永久存储
不足
  • 浏览器大小规范不统一,而且需要IE8以上才支持
  • 值的类型限制在String,可能需要一些转换才能达到我们的目的
  • 不能被爬虫抓取
  • 遵循同源策略,不同协议/域名/端口下的localStorage是不能共用的
localStorage的基本使用
  • 写入一个普通数组

    const arr = [1,2,3]
    //通过localStorage的setItem方法,第一个参数传入要设置的localStorage的名称,第二个参数传入要存储的数据
    localStorage.setItem('arr',arr)
    //通过localStorage的getItem方法,传入要查询的localStorage的名称
    console.log(localStorage.getItem('arr'))
    //推荐下面这种获取方法,避免了查询不存在的存储返回null
    console.log(localStorage.getItem('arr') || '[]')
    
  • 如何判断成功存储在本地呢?我们可以通过谷歌chrome来查看.

    • 打开对应的页面
    • 按F12调出开发者工具,选择Application选项
    • 在左侧选择Storage栏的Local Storage即可查看相应的存储
    • 当然也包括了Session Storage,webSQL等的存储,有需要的可以自行查看
    • 在这里插入图片描述
  • 其他存储普通类型数据不再依次展示.很多时候我们需要存储的是复杂的数据类型.比如数组或对象,这时如果通过和传入普通数组一样的方式是会出现错误的.例如:

    //如果我们想存储某个NodeList
    <div>
        <p>1</p>  
        <p>2</p>
        <p>3</p>
    </div>
    <script>
        const p = document.querySelectorAll('p')
        localStorage.setItem('p',p)
        console.log(localStorage.getItem('p'))
    </script>
    //期望之中是将获取到的3个p全部存储起来,但实际上打印出的是:[object NodeList]这么一个东西
    //其实这是localStorage在存储的时候要先将p这个类数组转换为字符串,而且由于3个p转换的都是同样的[object NodeList],因此最后只存储了一个字符串
    
  • 如果我们想存储复杂数据类型,可以通过JSON.stringify和JSON.parse的转换来实现

    const arr = [{name:'张三',age:20},{name:'李四',age:25},{name:'王五',age:30}]
    //将数组先转化为字符串
    localStorage.setItem("userInfo",JSON.stringify(arr))	
    //再将字符串转化为数组对象,这样就可以将数组正确存储
    console.log(JSON.parse(localStorage.getItem('userInfo')))	
    
  • 删除localStorage: localStorage.clear('name') 输出需要删除的名称即可

项目练习(菜单添加删除,本地化存储)
  • 可直接copy查看效果,体会localStorage的用法
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>LocalStorage</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <!--
      Fish SVG Cred:
      https://thenounproject.com/search/?q=fish&i=589236
   -->
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px"
        viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
        <g>
            <path
                d="M495.9,425.3H16.1c-5.2,0-10.1,2.9-12.5,7.6c-2.4,4.7-2.1,10.3,0.9,14.6l39,56.4c2.6,3.8,7,6.1,11.6,6.1h401.7   c4.6,0,9-2.3,11.6-6.1l39-56.4c3-4.3,3.3-9.9,0.9-14.6C506,428.2,501.1,425.3,495.9,425.3z M449.4,481.8H62.6L43,453.6H469   L449.4,481.8z" />
            <path
                d="M158.3,122c7.8,0,14.1-6.3,14.1-14.1V43.4c0-7.8-6.3-14.1-14.1-14.1c-7.8,0-14.1,6.3-14.1,14.1v64.5   C144.2,115.7,150.5,122,158.3,122z" />
            <path
                d="M245.1,94.7c7.8,0,14.1-6.3,14.1-14.1V16.1c0-7.8-6.3-14.1-14.1-14.1C237.3,2,231,8.3,231,16.1v64.5   C231,88.4,237.3,94.7,245.1,94.7z" />
            <path
                d="M331.9,122c7.8,0,14.1-6.3,14.1-14.1V43.4c0-7.8-6.3-14.1-14.1-14.1s-14.1,6.3-14.1,14.1v64.5   C317.8,115.7,324.1,122,331.9,122z" />
            <path
                d="M9.6,385.2c5.3,2.8,11.8,1.9,16.2-2.2l50.6-47.7c56.7,46.5,126.6,71.9,198.3,71.9c0,0,0,0,0,0   c87.5,0,169.7-36.6,231.4-103.2c5-5.4,5-13.8,0-19.2c-61.8-66.5-144-103.2-231.4-103.2c-72,0-142.2,25.6-199,72.5l-50-47.1   c-4.4-4.1-10.9-5-16.2-2.2c-5.3,2.8-8.3,8.7-7.4,14.6l11.6,75L2.2,370.6C1.3,376.5,4.2,382.4,9.6,385.2z M380.9,230.8   c34.9,14.3,67.2,35.7,95.3,63.6c-10.1,10-20.8,19.2-31.9,27.5c-22.4-3.3-29.6-8.8-30.7-9.7c-4-5.7-11.8-7.7-18.1-4.4   c-6.9,3.6-9.5,12.2-5.9,19.1c1.9,3.5,7.3,10.3,22.4,16c-10.1,5.7-20.5,10.7-31.1,15.1C352.4,320.2,352.4,268.6,380.9,230.8z    M36.3,255.6l29.4,27.7c5.3,5,13.6,5.1,19.1,0.3c53.2-47.6,120.7-73.7,190-73.7c26.9,0,53.2,3.9,78.5,11.3   c-29.3,44.6-29.3,102,0,146.6c-25.3,7.4-51.6,11.3-78.5,11.3c-69,0-136.3-26-189.4-73.2c-2.7-2.4-13.4-6.3-19.1,0.3l-30.1,28.3   l5.7-40C42.2,293,36.3,255.6,36.3,255.6z" />
            <circle cx="398.8" cy="273.8" r="14.1" />
        </g>
    </svg>
    <div class="wrapper">
        <h2>LOCAL TAPAS</h2>
        <p></p>
        <ul class="plates">
            <!-- <li>Loading Tapas...</li> -->
        </ul>
        <form class="add-items">
            <input type="text" name="item" placeholder="Item Name" required autocomplete="off">
            <input type="submit" value="Add Item">
            <input class="check-all" type="button" value="Check All">
	        <input class="uncheck-all" type="button" value="Uncheck All">
	        <input class="delete-all" type="reset" value="Delete All">
        </form>
    </div>
    <script>
        // <input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} >
        //         <label for="item${i}">${plate.text}</label>
        window.onload = function () {
            const addItems = document.querySelector('.add-items')
            const itemsList = document.querySelector('.plates')
            const checkAll = document.querySelector('.check-all')
            const uncheckAll = document.querySelector('.uncheck-all')
            const deleteAll = document.querySelector('.delete-all')
            let items = JSON.parse(localStorage.getItem('arr2') || '[]')
            displayList()
            addItems.addEventListener('submit', function (e) {
                e.preventDefault()
                const text = this.querySelector('[name=item]').value
                const item = {
                    text,
                    checked: false
                }
                items.push(item)
                displayList()
                this.querySelector('[name=item]').value = ''
                localStorage.setItem('arr2', JSON.stringify(items))
            })
            checkAll.addEventListener('click',function(e) {
                items.forEach(e => {
                    e.checked = true
                })
                localStorage.setItem('arr2', JSON.stringify(items))
                displayList()
            })
            uncheckAll.addEventListener('click',function(e) {
                items.forEach(e => {
                    e.checked = false
                })
                localStorage.setItem('arr2', JSON.stringify(items))
                displayList()
            })
            deleteAll.addEventListener('click',function(e) {
                localStorage.clear('arr2')
                items = []
                displayList()
            })
            function displayList() {
                itemsList.innerHTML = ''
                items.forEach((e,i) => {
                    const li = document.createElement('li')
                    li.innerHTML = `
                        <input type="checkbox" data-index=${i} id="item${i}" ${e.checked ? 'checked' : ''} >
                        <label for="item${i}">${e.text}</label>
                    `
                    itemsList.appendChild(li)
                })
            }
        }
    </script>
</body>

</html>
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值