检查cookie是否存在的好方法是什么?
条件:
Cookie存在,如果
cookie1=;cookie1=345534; //or cookie1=345534;cookie1=; //or cookie1=345534;
如果不存在Cookie,
cookie=; //or <blank>
您可以使用所需cookie的名称调用函数getCookie,然后检查其是否为null。
function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } } // because unescape has been deprecated, replaced with decodeURI //return unescape(dc.substring(begin + prefix.length, end)); return decodeURI(dc.substring(begin + prefix.length, end)); } function doSomething() { var myCookie = getCookie("MyCookie"); if (myCookie == null) { // do cookie doesn't exist stuff; } else { // do cookie exists stuff } }