【问题标题】:Can someone help me debug a 'once-per-session' cookie with a addClass & removeClass function?有人可以帮我调试一个带有 addClass 和 removeClass 功能的“每会话一次”cookie吗?
【发布时间】:2012-08-11 13:28:14
【问题描述】:

我找到了以下 JS 代码(根本不是我的,我不相信。感谢 Michael Regan,www.owt4nowt.ca)

所以,代码:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script>
var key_value = "myTestCookie=true";
var foundCookie = 0;

// Get all the cookies from this site and store in an array
var cookieArray = document.cookie.split(';');

    for(var i=0;i < cookieArray.length;i++)
        {
               var checkCookie = cookieArray[i];
               while (checkCookie.charAt(0)==' ')
               {
                 checkCookie = checkCookie.substring(1,checkCookie.length);
               }

                if (checkCookie.indexOf(key_value) == 0)
               {
                  alert("Found Cookie ");
                   foundCookie = 1;
               }
    }
    if ( foundCookie == 0)
    {
        document.cookie = key_value;
        alert("Setting Cookie");
    }  
</script>

警报正常工作。

但是,当 cookie 被识别时,我删除了警报:

        if (checkCookie.indexOf(key_value) == 0)
       {
           foundCookie = 1;
       }

我用 addClass 函数替换了“设置 Cookie”警报,或者我是这么认为的。

if ( foundCookie == 0)
{
    document.cookie = key_value;
    $('.someClassHere').addClass("newClass");
}  

问题是该功能根本不起作用。如果只留给alerts也没问题,但是addClass函数完全被忽略了。

addClass 函数有语法错误吗?

【问题讨论】:

  • 您错过了一个实际问题!有什么不工作吗?你收到错误了吗?
  • 我更新了帖子,感谢您对含糊不清的提醒
  • 看起来您正在尝试使用 jQuery - 您是否包含了 jQuery 库?
  • 我已包含指向 Google 1.7.2 链接的链接
  • 您能否在问题中添加您如何链接到 jQuery。

标签: javascript session cookies addclass


【解决方案1】:

在收到很多好的cmets和tips之后,最好的结果是“alun”建议将javascript包装在一个jQuery .ready() API中。

脚本在添加(或删除)类时的有效性存在明显延迟,但至少功能存在,通过 CSS 等的正确组合,可以最大限度地减少中断。

我使用的成功代码是:

<script type="text/javascript">
$(document).ready(function () {
 var key_value = "myTestCookie=true";
 var foundCookie = 0;
 var cookieArray = document.cookie.split(';');
     for(var i=0;i < cookieArray.length;i++)
         {
                var checkCookie = cookieArray[i];
                while (checkCookie.charAt(0)==' ')
                {
                  checkCookie = checkCookie.substring(1,checkCookie.length);
                }
                 if (checkCookie.indexOf(key_value) == 0)
                {
                    foundCookie = 1;
                }
     }
     if ( foundCookie == 0)
     {
         document.cookie = key_value;
       $('.someClassOne').removeClass("extraClass");
     } 
});
</script> 

所以,是的,我希望这对其他人有帮助!

感谢论坛!

/布莱恩

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2016-07-05
    • 2013-01-07
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多