javscript对cookie的操作,以及封装
生活随笔
收集整理的這篇文章主要介紹了
javscript对cookie的操作,以及封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Document</title>
</head>
<body>用戶名:<input type="text" name="user" id="user">年齡:<input type="text" name="age" id="age"><input type="button" name="" value="提交" id="btn">
</body>
</html>
JS代碼
<script type="text/javascript">// 設置cookiefunction setCookie(){// 獲取當前時間var date = new Date();// 支持傳一個json {name:value}var a = arguments;if(a.length==2){// 設置過期時間 = 當前時間 + 過期時間;date.setDate(date.getDate()+a[1]);for(k in a[0]){document.cookie = k +"="+ encodeURI(a[0][k]) +";expires=" + date.toGMTString()+";path=/";}}else{date.setDate(date.getDate()+a[2]);// 設置cookie = 值=value encodeURI(把值進行編碼) expires設置過期時間 path設置網站目錄訪問cookie權限,/表示當前域名下的所有目錄都可以訪問這個cookiedocument.cookie = a[0] +"="+ encodeURI(a[1]) +";expires=" + date.toGMTString()+";path=/";}}// 讀取cookiefunction readCookie(name){// 獲取cookie decodeURI把cookie進行解碼var cookie = decodeURI(document.cookie);// 獲取當前名稱的起始索引var start = cookie.indexOf(name+'=');// 如果找不到這個名稱的話就直接返回;if(start==-1)return '';// 獲取結束索引,start表示開始查找的起點var end = cookie.indexOf(';',start);// 如果返回-1說明是最后一條數據if(end==-1){// 最后一條直接截取到末尾return cookie.substring(start+name.length+1);}// 如果不是末尾的話截取到;return cookie.substring(start+name.length+1,end);}// 刪除cookiefunction removeCookie(name){document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";}// 寫入cookievar oBtn = document.getElementById('btn');oBtn.onclick = function(){var user = document.getElementById('user').value;var age = document.getElementById('age').value;// 設置cookiesetCookie({'user':user,'age':age},10);};// 打印cookieconsole.log(readCookie('user')); </script>
使用方法:
設置cookie:setCookie()支持傳遞2個或3個參數 json&&time || nam&&value&&time ? ? ? ? ? ? ?json:{name:value},time:多久過期
讀取cookie:readCookie(要讀取的cookie名稱)
刪除cookie:removeCookie(要刪除的cookie名稱)
以上也是閑來無事寫的,僅供參考,如果有不懂的可以在下方留言,如果多人需要幫助的話我再另外開一片文章專門講。
轉載于:https://www.cnblogs.com/pssp/p/5701066.html
總結
以上是生活随笔為你收集整理的javscript对cookie的操作,以及封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 架构实例之Demo_JSP
- 下一篇: while、do while练习——7月