简体   繁体   English

Javascript集然后显示一个cookie值

[英]Javascript set then display a cookie value

My problem seems to be easy but I can't make it work; 我的问题似乎很简单,但我无法解决。 I want to set a cookie variable called "splash" then display it (later I want use in IF clause) Here is my code : 我想设置一个名为“ splash”的cookie变量,然后显示它(稍后我想在IF子句中使用)这是我的代码:

<html>
   <head>
      <script type="text/javascript">
document.cookie =  "splash=" + encodeURIComponent("blue theme")
   var re = new RegExp(splash + "=([^;]+)");
    var value = re.exec(document.cookie);
    alert(value);
   </script>
   </head>
 <body>
 </body>
</html>

You should change your regex to include splash as part of the quoted string. 您应该更改正则表达式以将splash包含在引用的字符串中。 Even though spash is the variable you're using in the cookie, it does not automatically become a javascript variable. 即使spash是您在Cookie中使用的变量,它也不会自动成为javascript变量。

document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp("splash=([^;]+)");
var theme = re.exec(document.cookie)[1];

re.exec returns an array. re.exec返回一个数组。 the first element is the entire matched string (including splash= ). 第一个元素是整个匹配的字符串(包括splash= )。 The second is your capture group ( blue%20theme ). 第二个是您的捕获组( blue%20theme )。

Use Following function to set and get Cookie 使用以下功能设置和获取Cookie

function createCookie(name, value, days)
{
    if(days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    var fixedName = '';
    name = fixedName + name;
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) 
{
   var value = "; " + document.cookie;
   var parts = value.split("; " + name + "=");
   if (parts.length == 2) return parts.pop().split(";").shift();
}
function eraseCookie(name) 
{
    createCookie(name, "", -1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM