1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- // 设置cookie
- function setCookie(key,value,timer){
- // 设置key 和 value
- var keyVal = key + "=" + value;
- // 设置过期时间
- var now = new Date();
- now.setDate(now.getDate() + timer);
- var timerStr = ";expires=" + now.toUTCString();
- // 设置cookie
- document.cookie = keyVal + timerStr;
- }
- // 获取cookie
- function getCookie(key){
- // 获取所有cookie
- var thisCookie = document.cookie;
- // 拆分cookie
- var cookieArr = thisCookie.split(";");
- // 遍历cookie
- for(var i=0;i<cookieArr.length;i++){
- var cookieKey= cookieArr[i].split("=");
- // trim()去除字符串左右空格
- // console.log(cookieKey[0].trim());
- if(cookieKey[0].trim() == key){
- return cookieKey[1]
- }
- }
- }
- // 删除cookie
- function delCookie(key){
- // 设置cookie 过期时间为-1
- setCookie(key,'',-1);
- }
- // 设置一个cookie name=张三 过期时间为10天后
- setCookie('name','张三',10);
- setCookie('age',18,10);
- setCookie('sex','男',10);
- // 获取cookie
- console.log(getCookie('sex'));
- // 删除cookie
- delCookie('sex');
- </script>
- </body>
- </html>
|