Saving Cookies To A Javascript Associative Array
I'm having trouble with cookies. I have a bunch of links that when clicked on, create a cookie. For each link I need to be able to save that cookie to an associative array. The tricky part is the cookie values are dynamically created. We don't know what they are until they are clicked on (using the id attribute).
Here is the click function I'm using to create the cookie:
$j('a.createCookie').click(function(e) {
var cookieName = "InsightsCookie";
var cookieValue = $j(this).attr("id");
$j.cookie(cookieName, cookieValue, {expires: 365, pa开发者_运维百科th: '/'});
});
Any help would be much appreciated.
To save the cookies to a global associative array, you would do something like this:
var my_global_assoc_array = {};
$j('a.createCookie').click(function(e) {
var cookieName = "InsightsCookie";
var cookieValue = $j(this).attr("id");
$j.cookie(cookieName, cookieValue, {expires: 365, path: '/'});
// save just the value of the cookie
my_global_assoc_array[cookieName] = cookieValue;
// or save the whole cookie because you may want to know more about the cookie path, cookie expiration, etc
my_global_assoc_array[cookieName] = $j.cookie(cookieName);
});
Then at some later point, you can iterate over what's been collected in your assoc array:
for(var i in my_global_assoc_array)
console.log("cookie name = " + i + ", cookie value = " + i);
I'm confused about this part of your question: "The tricky part is the cookie values are dynamically created." Since the cookie values are just values in the my_global_assoc_array, why do you need to know what the values are beforehand?
Update
If you want a single cookie to contain all the values of my_global_assoc_array then use a loop in the set cookie routine. Something like this:
var my_global_assoc_array = {};
$j('a.createCookie').click(function(e) {
var cookieName = "InsightsCookie";
var cookieValue = $j(this).attr("id");
// save all values of the cookie in an assoc array to uniqueify the list.
my_global_assoc_array[cookieValue] = 0;
// temporarily turn cookieValue into an Array, add all the cookieValues to it and
// use join to stringify it to a CSV value of the values.
cookieValue = new Array();
for(var i in my_global_assoc_array)
cookieValue.push(i);
cookieValue = cookieValue.join(',');
// store cookieValue which is now a CSV list of cookieValues
$j.cookie(cookieName, cookieValue, {expires: 365, path: '/'});
});
精彩评论