javascript - 如何检查 cookie 是否存在?

标签 javascript html cookies

检查 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
    }
}

关于javascript - 如何检查 cookie 是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5968196/

相关文章:

javascript - 将 jQuery 插件 Pagination.js 与 React 结合使用

javascript - 固定标签更新通知

javascript - 多个实例,相同的 ID

html - 调整 float 导航栏中 Logo 的大小

javascript - 用于管理 cookie 的 jquery 插件

javascript - 如何编写脚本来检测网站上的 Activity 按钮?

javascript - Greasemonkey - 查找链接并添加另一个链接

javascript - 使用 document.createElement 创建 html 元素时更改其在父标记中的位置

jsf - 在JSF2.0中,如何在facelets中写出cookies?

c# - 无法通过操作设置 cookie