javascript - 无法正确检查现有 cookie

标签 javascript if-statement cookies

我错过了一些非常简单的东西......

我有一个设置 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() 是以前对我有用的通用函数。

JSFIDDLE here .

最佳答案

您在以下行中遇到问题:

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/

相关文章:

javascript - 直到页面刷新,JQuery 才会运行

date - 在 Google 表格中设置列默认值

javascript - 从 Angular 选择框中再次选择 "selected element"

javascript - 在 React 中获取组件子组件的类型

javascript - 如何在类组件中使用 react-router-dom v6 导航

php - 例如,使用 cookie 加速 web 应用程序

javascript - 谷歌分析非法 cookie 破坏 Python 后端

python - pandas 中的条件

java - if、else if、else 中的调试器行为

javascript - 使用localStorage存储jQuery范围 slider 的最大值和最小值