10_本地存储.html 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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()
  27. function getCookie (key) {
  28. var cookie = document.cookie
  29. console.log(cookie)
  30. /*
  31. 创建一个数组 存放分开这个字符串
  32. .split 把字符串 拆分成数组
  33. ["password='123'", ' undefined=undefined', " name='zs'"]
  34. */
  35. var arr = cookie.split(';')
  36. console.log(arr)
  37. for(var i=0;i<arr.length;i++){
  38. var tmp = arr[i].split('=')
  39. console.log(tmp)
  40. /* trim() 方法 用于删除字符串的头尾空白符 */
  41. if(tmp[0].trim() == key){
  42. return tmp[1]
  43. }
  44. }
  45. }
  46. console.log(getCookie('undefined'))
  47. function delCookie(key){
  48. var date = new Date()
  49. date.setDate(date.getDate() - 1 )
  50. document.cookie = key + '=null;expires=' + date.toUTCString()
  51. }
  52. delCookie('password')
  53. </script>
  54. </body>
  55. </html>