10_本地存储.html 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. /*
  12. cookie 本地存储 大小 4K 默认的有效期 为当前对话窗口
  13. 可以通过 expires 设置过期时间
  14. */
  15. document.cookie = "name = 'zs'"
  16. var date = new Date()
  17. date.setDate(date.getDate() + 1)
  18. console.log(date)
  19. console.log(date.toUTCString())
  20. document.cookie = "password = '123';expires="+date.toUTCString()
  21. function setCookie (key,value,expires){
  22. var date = new Date()
  23. date.setDate(date.getDate()+expires)
  24. document.cookie = key + '=' +value + ';expires=' + date.toUTCString()
  25. }
  26. setCookie('age',18,2)
  27. function getCookie(key){
  28. var cookie = document.cookie
  29. console.log(cookie)
  30. /* 创建一个arr 存放字符串分开
  31. .split() 把字符串 拆分成数组
  32. ["password='123'", " name='zs'", ' age=18']
  33. */
  34. var arr = cookie.split(';')
  35. console.log(arr)
  36. for(var i=0;i<arr.length;i++){
  37. var tmp = arr[i].split('=')
  38. console.log(tmp)
  39. /* trim()用于删除字符串的头尾空白 */
  40. if(tmp[0].trim() == key){
  41. return tmp[1]
  42. }
  43. }
  44. }
  45. console.log(getCookie('age'))
  46. function delCookie(key){
  47. var date = new Date()
  48. date.setDate(date.getDate()-1)
  49. document.cookie = key+ '=null;expires='+ date.toUTCString()
  50. }
  51. delCookie('age')
  52. </script>
  53. </body>
  54. </html>