<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script> //子可以看到父,但是父不可以看到子; console.log(typeof document.cookie); //string console.log(document.cookie === ""); //true // 增 document.cookie = "pass=123121"; //d多了一条cookie var d = new Date(); d.setDate(d.getDate()+3); document.cookie = "user=admin;expires="+d; //设置销毁的时间 // 一个document.cookie只能设置一条cookie document.cookie = "b=20;path=/1908"; //path设置cookie在的指定位置.字可以设置父,但是父不能设置子; document.cookie = "b=20;"; document.cookie = "c=30;path=/1908;expires=" + d; document.cookie = "d=40;expires="+d; // 改 document.cookie="user=root"; //上面的admin会被改成root document.cookie = "b=world;path=/1908"; var d = new Date(); d.setDate(d.getDate()+5); document.cookie = "c=30;path=/1908;expires="+d; // 删: var e = new Date(); e.setDate(e.getDate()-3); document.cookie="user=root;expires="+e; //user这条cookie的销毁时间设置成三天前,那么这条cookie就相当于被删除了 var d = new Date(); d.setDate(d.getDate()-1); document.cookie = "a=10;path=/1908;expires="+d; document.cookie = "b=10;path=/1908;expires="+d; //查 console.log(document.cookie) </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=\, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script> // setCookie("a","10") // setCookie("b","20",{}) // setCookie("c","30",{ // path:"/" // }) // setCookie("d","40",{ // expires:3 // }) // setCookie("e","50",{ // expires:3, // path:"/" // }) // setCookie("e","60",{ // expires:3 // }) // removeCookie("e",{ // path:"/" // }) // removeCookie("a",{}) // removeCookie("b") // getCookie() function setCookie(key,val,options){ // 处理默认的options options = options || {}; // 处理默认的路径 var path = ""; if(options.path){ path = ";path=" + options.path; } // 处理默认的有效期 var expires = ""; if(options.expires){ var d = new Date(); d.setDate(d.getDate()+options.expires); expires = ";expires=" + d; } // 设置cookie document.cookie = key + "="+ val + path + expires; } function removeCookie(key,options){ // 处理默认的options options = options || {}; // 有效期设置为昨天,实现删除 // 先设置有效期字段:为-1 options.expires = -1; // 调用设置cookie,将实现删除的日期和指定路径传过去 setCookie(key,132,options); } </script> </html>