我有一个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(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 :-(');
}
我会这样做:
function getCookie(cookie){
return cookie
.trim()
.split(';')
.map(function(line){return line.split(',');})
.reduce(function(props,line) {
var name = line[0].slice(0,line[0].search('='));
var value = line[0].slice(line[0].search('='));
props[name] = value;
return props;
},{})
}
这将以对象的形式返回cookie。
然后你可以这样调用它:
getCookie(document.cookie)['shares']