我有一个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键值对分成一个数组,并基于你的搜索:
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示例:
JS:
document.cookies = {
create : function(key, value, time){
if (time) {
var date = new Date();
date.setTime(date.getTime()+(time*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
},
erase : function(key){
this.create(key,"",-1);
},
read : function(key){
var keyX = key + "=";
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,c.length);
if (c.indexOf(keyX) == 0) return c.substring(keyX.length,c.length);
}
return null;
}
}
使用json或xml存储数组和对象