如何使用js删除cookies?

发布网友 发布时间:2022-04-23 03:19

我来回答

2个回答

热心网友 时间:2022-04-20 11:33

<script language="JavaScript" type="text/javascript">
function addCookie(objName,objValue,objHours){//添加cookie
var str = objName + "=" + escape(objValue);
if(objHours > 0){//为0时不设定过期时间,浏览器关闭时cookie自动消失
var date = new Date();
var ms = objHours*3600*1000;
date.setTime(date.getTime() + ms);
str += "; expires=" + date.toGMTString();
}
document.cookie = str;
alert("添加cookie成功");
}

function getCookie(objName){//获取指定名称的cookie的值
var arrStr = document.cookie.split("; ");
for(var i = 0;i < arrStr.length;i ++){
var temp = arrStr[i].split("=");
if(temp[0] == objName) return unescape(temp[1]);
}
}

function delCookie(name){//为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间
var date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = name + "=a; expires=" + date.toGMTString();
}

function allCookie(){//读取所有保存的cookie字符串
var str = document.cookie;
if(str == ""){
str = "没有保存任何cookie";
}
alert(str);
}

function $(m,n){
return document.forms[m].elements[n].value;
}

function add_(){
var cookie_name = $("myform","cookie_name");
var cookie_value = $("myform","cookie_value");
var cookie_expireHours = $("myform","cookie_expiresHours");
addCookie(cookie_name,cookie_value,cookie_expireHours);
}

function get_(){
var cookie_name = $("myform","cookie_name");
var cookie_value = getCookie(cookie_name);
alert(cookie_value);
}

function del_(){
var cookie_name = $("myform","cookie_name");
delCookie(cookie_name);
alert("删除成功");
}
</script>

热心网友 时间:2022-04-20 12:51

function DelCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
document.cookie = name + "=; expires=" + exp.toGMTString();
}
DelCookie(要删除的cookie名);追问DelCookie在ie下报错

追答我又试了一遍,没错啊。报的什么错?是不是调用时传过去的cookie名没有加引号?
要这样:DelCookie(" cookie名 ");

参考资料:http://87cool.com

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com