写入和读取Cookie是一种常见的功能,可惜JavaScript对此的直接支持并不算完善,下面是几个操作Cookie的函数,用起来还是蛮方便的。
function getExpDate(days, hours, minutes) {
var expDate = new Date( );
if (typeof days == "number" && typeof hours == "number" &&
typeof hours == "number") {
expDate.setDate(expDate.getDate( ) + parseInt(days));
expDate.setHours(expDate.getHours( ) + parseInt(hours));
expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));
return expDate.toGMTString( );
}
}
function getCookieVal(offset) {
var endstr = documents.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = documents.cookie.length;
}
return unescape(documents.cookie.substring(offset, endstr));
}
function getCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = documents.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (documents.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = documents.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return "";
}
function setCookie(name, value, expires, path, domain, secure) {
documents.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function deleteCookie(name,path,domain) {
if (getCookie(name)) {
documents.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
将上面的几个js命名为cookie.js,下面演示其基本用法
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
function foo()
{
var name = document.getElementById("name").value;
if(name)
{
setCookie("name",name);
}
document.getElementById("show").innerHTML+=("NEWEST NAME :"+ getCookie("name") + "<br>");
}
</script>
Chapter 1.9 example
<br>
<input type="text" id="name" size="20" />
<input type="button" value="setCookie" onclick="foo()" />
<div id="show"></div>