Javascript Cookie问题IE

时间:2010-05-14 14:05:38

标签: javascript cookies internet-explorer

一直在用一些Javascript包装我的头,请帮忙,我不明白为什么它根本不会在IE 7或8中找到我的cookie

我通过另一个事件将cookie设置为true,但我只是想看到IE拿起我最初设置的cookie。也可以在firefox中使用,提前谢谢。

var t=setTimeout("doAlert()",8000);
var doAlertVar = true;
document.cookie =  "closed=0;expires=0;path=";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie;
    alert(ca);
    ca = ca.replace(/^\s*|\s*$/g,'');
    ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function doAlert(){

    if(readCookie('closed')==1){
        doAlertVar = false;
    }
    if(readCookie('closed')==0){
        alert("unlicensed demo version\nbuy online at");

    }
    t=setTimeout("doAlert()",5000);

}

2 个答案:

答案 0 :(得分:1)

从哪里开始......

setTimeout("doAlert()",8000);
// do not use strings as an argument to setTimeout, that runs eval under the hood.
// use
setTimeout(doAlert,8000);
// instead

document.cookie =  "closed=0;expires=0;path=";
// this is wrong, expires should follow the format Fri, 14 May 2010 17:22:33 GMT (new Date().toUTCString())
// path should be path=/

答案 1 :(得分:0)

您也可以使用正则表达式执行此操作:

function readCookie(name, defaultValue) {
  var value = defaultValue;
  document.cookie.replace(new RegExp("\\b" + name + "=([^;]*)"), function(_, v) {
    value = v;
  });
  return value;
}