我有一个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值,而不需要任何外部库:

const value = ('; '+document.cookie).split(`; COOKIE_NAME=`).pop().split(';')[0];

这个答案是基于kirlich的聪明的解决方案。这个解决方案的唯一妥协是,当cookie不存在时,您将得到一个空字符串。不过,在大多数情况下,这不应该成为交易破坏者。

其他回答

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

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 :-(');
}

如果你使用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');

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')

查找现有cookie的功能性方法。它返回一个数组,因此它支持同一名称多次出现。它不支持部分键匹配,但是用正则表达式替换过滤器中的=== =是很简单的。

function getCookie(needle) {
    return document.cookie.split(';').map(function(cookiestring) {
        cs = cookiestring.trim().split('=');

        if(cs.length === 2) {
            return {'name' : cs[0], 'value' : cs[1]};
        } else {
            return {'name' : '', 'value' : ''};
        }
    })
    .filter(function(cookieObject) { 
        return (cookieObject.name === needle);
    });
}

我更喜欢在cookie上使用一个正则表达式匹配:

window.getCookie = function(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  if (match) return match[2];
}

也可以作为函数使用,检查下面的代码。

function check_cookie_name(name) 
    {
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) {
        console.log(match[2]);
      }
      else{
           console.log('--something went wrong---');
      }
   }

感谢Scott Jungwirth的评论。