我有一个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]);
    }
 }

当前回答

总是很有效:

function getCookie(cname) {
    var name = cname + "=",
        ca = document.cookie.split(';'),
        i,
        c,
        ca_length = ca.length;
    for (i = 0; i < ca_length; i += 1) {
        c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) !== -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(variable, value, expires_seconds) {
    var d = new Date();
    d = new Date(d.getTime() + 1000 * expires_seconds);
    document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}

对jQuery或任何东西都没有要求。纯粹的老JavaScript。

其他回答

由javascript设置

document.cookie = 'cookiename=tesing';

使用jquery-cookie插件来学习jquery

var value = $.cookie("cookiename");

alert(value);

现在,当以数组格式存储cookie时,可以让cookie以数组形式返回。 例如,你的cookie数组[35]=Khóa;数组[36]= Tử;数组[37]= Cử; 这段代码也包含utf8。 当你的cookie名称内容[]在其中,而你存储的cookie不在数组中时,一件事不会很好地工作。

function getCookie(cname) {

            var ca = decodeURIComponent(document.cookie).split(';');


            if (cname.indexOf('[]') > 0) {
                var returnVAlue = [];
                var nameArray = cname.replace("[]", "");

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }

                    if (c.indexOf(nameArray) >= 0) {
                        var valueString = c.substr(nameArray.length, c.length);

                        var valueStringSlit = valueString.split('=');
                        valueStringSlit[0] = valueStringSlit[0].substr(1,(valueStringSlit[0].length - 2));
                    //    console.log(valueStringSlit);

                        returnVAlue.push(valueStringSlit);
                    }
                }
            } else {
                var returnVAlue = '';
                var name = cname + "=";

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }
                    if (c.indexOf(name) == 0) {
                        returnVAlue = c.substr(name.length, c.length);
                    } 
                }
            }


            if (returnVAlue != ''){
                return returnVAlue;
            } 
            return "";
        }

       // console.log(decodeURIComponent(document.cookie));


        console.log(getCookie('array[]'));

这个方法开箱即用,效果非常好

function getCookie(cname) {
  var cookies = ` ${document.cookie}`.split(";");
  var val = "";
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].split("=");
    if (cookie[0] == ` ${cname}`) {
      return cookie[1];
    }
  }
  return "";
}

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

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

var obligations = getCookie('obligations');
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