cookie 寫入的封裝,讀取的封裝,刪除某個屬性的封裝html
<!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> <button class="btn">按鈕</button> <script> function setCookie(attr,value,expires){ var date=new Date(); var time =date.getTime()+expires*24*3600*1000; date.setTime(time); document.cookie=attr+"="+value+";expires="+date.toUTCString() } setCookie("dfc",11,1); setCookie("lx",222,1); setCookie("hh",33,1); function getCookie(attr) { var cookie=document.cookie; var arr=cookie.split(";"); var newArr=[]; var obj={}; for(var i=0;i<arr.length;i++){ newArr=arr[i].split("="); //console.log(newArr) obj[newArr[0].trim()]=newArr[1] } console.log(obj) return obj[attr] } var aa= getCookie("dfc"); console.log(aa) function removeCookie(attr){ var cookie=document.cookie; var arr=cookie.split(";"); var newArr=[]; var obj={}; for(var i=0;i<arr.length;i++){ newArr=arr[i].split("="); //console.log(newArr) if(newArr[0].trim()!=attr){ obj[newArr[0].trim()]=newArr[0] } } return obj } document.querySelector(".btn").onclick=function () { var newObj=removeCookie("dfc"); console.log(newObj) } </script> </body> </html>