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

当前回答

如果你使用jQuery,我建议你使用这个插件:

https://github.com/carhartl/jquery-cookie https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

<script type="text/javascript"
 src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">

所以你可以这样读cookie:

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

你也可以写cookie:

$.cookie('obligations', 'new_value');
$.cookie('obligations', 'new_value', { expires: 14, path: '/' });

删除cookie:

$.removeCookie('obligations');

其他回答

参考:https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

document.cookie = "test1=Hello";
document.cookie = "test2=World";

var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

  alert(cookieValue);
function getCookie(cname) {
  var name = cname + "=";
  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);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

将cookie名称传递给getCookie()函数以获取它的值

我写了一些可能很容易使用的东西,如果有人有什么要补充的,请随时这样做。

function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

使用

Getcookie() -返回一个包含网页上所有cookie的对象。

getcookie('myCookie') -从cookie对象返回cookie myCookie的值,否则如果cookie为空或未设置则返回undefined。


例子

// Have some cookies :-)
document.cookie = "myCookies=delicious";
document.cookie = "myComputer=good";
document.cookie = "myBrowser=RAM hungry";

// Read them
console.log( "My cookies are " + getcookie('myCookie') );
// Outputs: My cookies are delicious

console.log( "My computer is " + getcookie('myComputer') );
// Outputs: My computer is good

console.log( "My browser is " + getcookie('myBrowser') );
// Outputs: My browser is RAM hungry

console.log( getcookie() );
// Outputs: {myCookie: "delicious", myComputer: "good", myBrowser: "RAM hungry"}

// (does cookie exist?)
if (getcookie('hidden_cookie')) {
    console.log('Hidden cookie was found!');
} else {
    console.log('Still no cookie :-(');
}

// (do any cookies exist?)
if (getcookie()) {
    console.log("You've got cookies to eat!");
} else {
    console.log('No cookies for today :-(');
}

在我看来,你可以把cookie键值对分成一个数组,并基于你的搜索:

var obligations = getCookieData("obligations");

运行如下:

function getCookieData( name ) {
    var pairs = document.cookie.split("; "),
        count = pairs.length, parts; 
    while ( count-- ) {
        parts = pairs[count].split("=");
        if ( parts[0] === name )
            return parts[1];
    }
    return false;
}

小提琴:http://jsfiddle.net/qFmPc/

或者甚至可能是以下内容:

function getCookieData( name ) {
    var patrn = new RegExp( "^" + name + "=(.*?);" ),
        patr2 = new RegExp( " " + name + "=(.*?);" );
    if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
        return match[1];
    return false;
}

现在,当以数组格式存储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[]'));