10_本地存储.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /* cookie大小4K */
  12. document.cookie = "name='zs'"
  13. var date = new Date()
  14. date.setDate(date.getDate() + 1)
  15. console.log(date)
  16. console.log(date.toUTCString())
  17. document.cookie = "password = '123';expires = " + date.toUTCString()
  18. function setCookie(key, value, expires) {
  19. var date = new Date()
  20. date.setDate(date.getDate() + expires)
  21. document.cookie = key + '=' + value + ';expires=' + date.toUTCString()
  22. }
  23. setCookie('address', 'harbin', 4)
  24. function getCookie(key) {
  25. var cookie = document.cookie
  26. console.log(cookie)
  27. /*
  28. 创建一个arr数组
  29. .split方法 把字符串拆分成数组
  30. ["name='zs'", " password='123'", ' address=harbin']
  31. */
  32. var arr = cookie.split(';')
  33. console.log(arr)
  34. for (var i = 0; i < arr.length; i++) {
  35. console.log(arr[i])
  36. var tmp = arr[i].split('=')
  37. console.log(tmp)
  38. /* trim() */
  39. if (tmp[0].trim() == key) {
  40. return tmp[1]
  41. }
  42. }
  43. }
  44. console.log(getCookie('name'))
  45. function delCookie(key) {
  46. var date = new Date()
  47. date.setDate(date.getDate() - 1)
  48. document.cookie = key + '=null;expires=' + date.toUTCString()
  49. }
  50. delCookie('password')
  51. </script>
  52. </body>
  53. </html>