我有一个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只需将cookie的名称传递给下面的函数

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.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 "";
}

其他回答

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

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 "";
}

4年后,ES6更简单的版本。

function getCookie(name) {
  let cookie = {};
  document.cookie.split(';').forEach(function(el) {
    let [k,v] = el.split('=');
    cookie[k.trim()] = v;
  })
  return cookie[name];
}

我还创建了一个主旨,将其用作Cookie对象。例如,Cookie.set(名称,值)和Cookie.get(名称)

这将读取所有cookie而不是扫描。少量的饼干是可以的。

下面的函数将返回所需cookie的一个键-值对,其中key是cookie名称,value是cookie的值。

/**
 * Returns cookie key-value pair
 */
var getCookieByName = function(name) {
    var result = ['-1','-1'];
    if(name) {
        var cookieList = document.cookie.split(';');
        result = $.grep(cookieList,function(cookie) { 
            cookie = cookie.split('=')[0];
            return cookie == name;
        });
    }
    return result;
};

在我看来,你可以把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;
}

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