我错过了一些非常简单的东西......
我有一个设置 cookie 的按钮:
<button id="gotit" >Got it</button>
JS:
$('#gotit').click(function () {
setCookie("gotIt", 'True', 30);
});
我有一个带有简单 if else 的 checkGetIt()
函数:
function checkGetIt() {
var gotIt = getCookie("gotIt");
if (gotIt === "") {
console.log('no such cookie'); // should do this until button pressed
} else {
console.log('cookie exists'); // this displays all the time, which is wrong
}
}
checkGetIt();
var z = document.cookie;
console.log('existing cookies: ' + z);
但我总是得到 console.log('cookie isn');
即使 console.log('existing cookies: ' + z);
之前什么也没给我单击按钮。
setCookie() 和 getCookie() 是以前对我有用的通用函数。
最佳答案
您在以下行中遇到问题:
if (gotIt === "")
将其更改为:
if (gotIt === null) // This will check for null.
或者:
if (gotIt == null) // This will check for null or undefined.
进一步阅读:Which equals operator (== vs ===) should be used in JavaScript comparisons?
除了检查“undefined or null”之外,您应该始终使用“===”(无类型转换),在这种情况下,最好的方法是比较“== null”。
关于javascript - 无法正确检查现有 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31988606/