Javascript中Cookie主要存储于客户端的计算机中,用于存放已访问的站点信息,Cookie最大约为4k.以下实例主要用于页面在刷新时保存数据,具体的用法如下所示:
<html> <head><title></title> </head> <body> <script type="text/javascript"> window.onload = function () { PersentValue(); } function AddValueToCookie() { setCookie("ID", 100); setCookie("Name", 'Tom'); PersentValue(); } function ClearValueOfCookie() { SetCookieToExpire("ID"); SetCookieToExpire("Name"); PersentValue(); } function PersentValue() { var id = getCookie("ID"); var name = getCookie("Name"); if (id == null) { alert('Waiting for set value to ID'); } else { alert(id); } if (name == null) { alert('Waiting for set value to Name'); } else { alert(name); } } function setCookie(name, value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); } function getCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) { return getCookieVal(j); } i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function getCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if (endstr == -1) { endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); } function SetCookieToExpire(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } </script> <input type="button" value="AddValue" onclick="AddValueToCookie();" /> <input type="button" value="ClearValue" onclick="ClearValueOfCookie();" /> </body> </html>