日期:2014-05-16  浏览次数:20346 次

js 中如何删除cookie 谢谢俺在线
JScript code
function setCookie(name,value,hours,path){  
 var name = escape(name);  
var value = escape(value);  
var expires = new Date();  
expires.setTime(expires.getTime() + hours*3600000);  
path = path == "" ? "" : ";path=" + path;  
_expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();  
document.cookie = name + "=" + value + _expires + path;  
}
以上为设置一个值到cookie中, 删除的时候,
function delCookie(name){
// setCookie(name,"",{expireDays:-1});
var date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = name + "=a; expires=" + date.toGMTString();
}  为什么这个方法delCookie()没有用呢,
 我在网上找的代码都不能删除很是郁闷, 
请各位帮我写个删除cookie的方法,   到底如何删除 cookie 
谢谢啦,


------解决方案--------------------
樓主參考一下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<style>
*{ font-size:12px;}
a{ color:#3399FF}
a:hover{ color:##3399FF}
a.hover{ color:#CC3300}
</style>
</head>
<body>
<div id="menu">
<a href="javascript:void(0)" class="hover" onclick="changename(0)">我是第一</a>
<a href="javascript:void(0)" onclick="changename(1)">我是第二</a>
<a href="javascript:void(0)" onclick="changename(2)">我是第三</a>
<a href="javascript:void(0)" onclick="changename(3)">我是第四</a>
</div>
<a href="javascript:clear();">点我清除cookie</a>
<script language="javascript">
function changename(c,cl)
{
var d=document.getElementById("menu").getElementsByTagName("a");
if(!cl)
{
writeCookie("hovers",c,222);
}
c=readCookie("hovers")?readCookie("hovers"):c;
for(i=0;i<d.length;i++)
{
d[i].className=i==c?"hover":"";
}
}
function writeCookie(name, value, hours)
{
var expire = "";
if(hours != null)
{
expire = new Date((new Date()).getTime() + 60 * 60 *1000);//+ hours
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
}
// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
var cookieValue = "";
var search = name + "=";
if(document.cookie.length > 0)

offset = document.cookie.indexOf(search);
if (offset != -1)

offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}
function clear()
{
writeCookie("hovers","",222);
document.location=document.location.href;
}
changename(0,1)
</script>
</body>
</html>
------解决方案--------------------
未经测试 你试试吧
JScript code

//添加cookie
function addCookie(objName,objValue,objHours){
   var str = objName + "=" + escape(objValue);
   if(objHours > 0){//为0时不设定过期时间,浏览器关闭时cookie自动消失
    var date = new Date();
    var ms = objHours*3600*1000;
    date.setTime(date.getTime() + ms);