簡體   English   中英

Javascript集然后顯示一個cookie值

[英]Javascript set then display a cookie value

我的問題似乎很簡單,但我無法解決。 我想設置一個名為“ 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>

您應該更改正則表達式以將splash包含在引用的字符串中。 即使spash是您在Cookie中使用的變量,它也不會自動成為javascript變量。

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

re.exec返回一個數組。 第一個元素是整個匹配的字符串(包括splash= )。 第二個是您的捕獲組( blue%20theme )。

使用以下功能設置和獲取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