ie和chrome下js操作cookie

来源:互联网 发布:淘宝网官网首页女装 编辑:程序博客网 时间:2024/06/07 18:30

本文参考:http://bbs.csdn.net/topics/390195613?page=1#post-397067687

http://www.w3school.com.cn/html5/html_5_webstorage.asp

http://tc.gaofen.com/?p=116

注:在原文基础上作部分改动。

代码示例:

<!DOCTYPE html><html><head></head><body><input type="button" id="input1" value="button1"></input></body><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script type="text/javascript">$("#input1").click(function(){/*// ie8下方案setCookie("userName","abc",24,"/");setCookie("password","123",24,"/");var userNameValue = getCookieValue("userName");var pwdValue = getCookieValue("password");console.log("---username:" + userNameValue);console.log("---pwd:" + pwdValue);*/// chrome下方案localStorage.username = 'abc';console.log("---localStorage username:" + localStorage.username);updatePageCountNoSession();updatePageCountWithSession();});function setCookie(name,value,hours,path){var name = escape(name);var value = escape(value);var expires = new Date();expires.setTime(expires.getTime() + hours * 60*60*1000);path = path =="" ? "":";path=" + path;_expires = (typeof hours) == "string" ? "": ";expires=" + expires.toUTCString();document.cookie = name + "=" + value + _expires + path;console.log("---cookie:" + document.cookie);}function getCookieValue(name){var name = escape(name);var allcookies = document.cookie;name += "=";var pos = allcookies.indexOf(name);if(pos != -1){var start = pos + name.length;var end = allcookies.indexOf(";",start);if(end == -1){end = allcookies.length;}var value = allcookies.substring(start,end);return unescape(value);} else{return "";}}function deleteCookie(name,path){var name = escape(name);var expires = new Date(0);path = path == "" ? "" : ";path=" + path;document.cookie = name + "=" + ";expires=" + expires.toUTCString() + path;}// 关闭浏览器后数据不会消失function updatePageCountNoSession(){// localStorage.pagecount与localStorage.getItem("pagecount")在此处均可用,// 不同的是:若pagecount不存在,前者返回undefined,后者返回null。if(localStorage.pagecount){localStorage.pagecount = Number(localStorage.pagecount) + 1;} else{localStorage.pagecount = 1;// 取值或设置值的两种方式// localStorage.setItem("pagecount",1);}console.log("---localStorage pagecount:" + localStorage.getItem("pagecount"));}// 关闭网页后数据会消失function updatePageCountWithSession(){if(sessionStorage.pagecount){sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;} else{sessionStorage.pagecount = 1;}console.log("---sessionStorage pagecount:" + sessionStorage.pagecount);}</script></html>
ie8方案输出:
日志: ---cookie:userName=abc; password=123
日志: ---cookie:userName=abc; password=123
日志: ---username:abc
日志: ---pwd:123

chrome方案输出:
---localStorage username:abc
---localStorage pagecount:11
---sessionStorage pagecount:1

注:输出11是由于我多次操作造成的。

0 0