Cookie的用法

设置cookie 函数

cookie 的名字(cname),cookie 的值(cvalue),以及知道 cookie 过期的天数(exdays)

1 function setCookie(cname, cvalue, exdays) {
2     var d = new Date();
3     d.setTime(d.getTime() + (exdays*24*60*60*1000));
4     var expires = "expires="+ d.toUTCString();
5     document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
6 }

调用

 1 setCookie('username','Bill Gates',3); 

获取cookie

 1 function getCookie(cname) {
 2     var name = cname + "=";
 3     var decodedCookie = decodeURIComponent(document.cookie);
 4     var ca = decodedCookie.split(';');
 5     for(var i = 0; i <ca.length; i++) {
 6         var c = ca[i];
 7         while (c.charAt(0) == ' ') {
 8             c = c.substring(1);
 9          }
10          if (c.indexOf(name) == 0) {
11             return c.substring(name.length, c.length);
12          }
13      }
14     return "";
15 } 

调用

 1 getCookie('username') 

检测cookie函数

 1 function checkCookie() {
 2     var username = getCookie("username");
 3     if (username != "") {
 4         alert("Welcome again " + username);
 5     } else {
 6         username = prompt("Please enter your name:", "");
 7         if (username != "" && username != null) {
 8             setCookie("username", username, 365);
 9         }
10     }
11 } 

cookie 进一步知识

js-cookie 插件

1.安装

 1 npm install js-cookie --save 

2.官方文档

https://github.com/js-cookie/js-cookie/tree/latest#readme

 

posted @ 2020-06-08 21:25  小凤凰之河北  阅读(449)  评论(0编辑  收藏  举报