設置Cookie並使用JavaScript獲取Cookie [重複]

本文翻譯自:Set cookie and get cookie with JavaScript [duplicate]

This question already has an answer here: 這個問題已經在這裏有了答案:

I'm trying to set a cookie depending on which CSS file I choose in my HTML. 我試圖根據我在HTML中選擇的CSS文件來設置Cookie。 I have a form with a list of options, and different CSS files as values. 我有一個帶有選項列表的表單,以及不同的CSS文件作爲值。 When I choose a file, it should be saved to a cookie for about a week. 當我選擇一個文件時,應將其保存到Cookie大約一週。 The next time you open your HTML file, it should be the previous file you've chosen. 下次打開HTML文件時,它應該是您選擇的上一個文件。

JavaScript code: JavaScript代碼:

function cssLayout() {
    document.getElementById("css").href = this.value;
}


function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML code: HTML代碼:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>

#1樓

參考:https://stackoom.com/question/z99z/設置Cookie並使用JavaScript獲取Cookie-重複


#2樓

Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS. 在W3Schools.com上檢查JavaScript Cookie,以通過JS設置和獲取Cookie值。

Just use the setCookie and getCookie methods mentioned there. 只需使用那裏提到的setCookie和getCookie方法。

So, the code will look something like: 因此,代碼將類似於:

<script>
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <option value="style-1.css">CSS1</option>
    <option value="style-2.css">CSS2</option>
    <option value="style-3.css">CSS3</option>
    <option value="style-4.css">CSS4</option>
</select>

#3樓

These are much much better references than w3schools (the most awful web reference ever made): 這些參考比w3schools(有史以來最糟糕的網絡參考) 好得多:

Examples derived from these references: 從這些參考文獻中得出的示例:

// sets the cookie cookie1
document.cookie =
 'cookie1=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie =
 'cookie2=test; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use. Mozilla參考文獻甚至有一個不錯的cookie庫供您使用。


#4樓

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs. 我確信這個問題應該有一個更通用的答案,其中包含一些可重複使用的代碼,這些代碼可將Cookie作爲鍵值對使用。

This snippet is taken from MDN and probably is trustable. 該摘錄取自MDN ,可能是可信的。 This is UTF-safe object for work with cookies: 這是用於Cookie的UTF安全對象:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases. Mozilla進行了一些測試,以證明此方法在所有情況下均有效。

There is an alternative snippet here : 還有一個另外的片段在這裏


#5樓

I find the following code to be much simpler than anything else: 我發現以下代碼比其他任何代碼都簡單得多:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

Now, calling functions 現在,調用函數

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html 來源-http: //www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now. 他們今天更新了頁面,因此頁面中的所有內容都應該是最新的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章