我有一个getter从cookie中获取值。

现在我有了两个cookie,名字分别是shares=和obligation =。

我想让这个getter只从义务cookie中获取值。

我怎么做呢?因此for语句将数据拆分为单独的值,并将其放入数组中。

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie? 
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

当前回答

cookie示例: JS:

document.cookies = {
   create : function(key, value, time){
     if (time) {
         var date = new Date();
         date.setTime(date.getTime()+(time*24*60*60*1000));
         var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = key+"="+value+expires+"; path=/";
   },
   erase : function(key){
     this.create(key,"",-1);
   },
   read : function(key){
     var keyX = key + "=";
     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(keyX) == 0) return   c.substring(keyX.length,c.length);
     }
     return null;
   }
}

使用json或xml存储数组和对象

其他回答

我知道这是一个老问题,但我也遇到过这个问题。只是为了记录,在开发者的mozilla网页中有一个小API。

你可以只使用JS获得任何名称的cookie。恕我直言,代码也更干净(除了很长的代码行,我相信您可以很容易地修改)。

function getCookie(sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

如注释中所述,注意此方法假定键和值是使用encodeURIComponent()编码的。如果cookie的键和值没有被编码,则删除decode & encodeURIComponent()。

使用object.defineProperty

有了这个,您可以轻松地访问cookie

Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});
    }
});

从现在起,你可以这样做:

alert( Cookies.obligations );

这也会自动更新,所以如果你改变了一个cookie, cookie也会改变。

JS中的Set-Cookie

document.cookie = 'fb-event-id=15648779++';

通过名称函数获取cookie

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    } 
    // Return null if not found
    return null;
}

这是如何使用getCookie函数

var eventID = getCookie('fb-event-id')
const cookies = 'key1=chocolate; key2=iceCream; key3=cookies;';

// convert string into array with split
const arrCookies = cookies.split('; '); // [ 'key1=chocolate', 'key2=iceCream', 'key3=cookies' ]

// split key value by equal sign
const arrArrCookiesKeyValue = arrCookies.map(cookie => [cookie.split('=')]);  // [[['key1', 'chocolate']], ...']

// make an object with key value
const objectKeyValueCookies = {}; // { key1: 'chocolate', key2: 'iceCream', key3: 'cookies;' }
for (let arr of arrArrCookiesKeyValue) {
    objectKeyValueCookies[arr[0][0]] = arr[0][1];
}

// find the key in object
const findValueByKey = (key = null, objectCookies) => objectCookies[key];
console.log(findValueByKey('key2', objectKeyValueCookies)); // chocolate

显然,MDN从未听说过单词边界正则表达式字符类\b,它与相邻的\w+相匹配,而\w+在两侧有界:

getCookie = function(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : null;
};

var obligations = getCookie('obligations');