要将 cookie 保存到全局关联数组,您可以执行以下操作:
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);
});
然后在稍后的某个时间点,您可以迭代在您的 assoc 数组中收集的内容:
for(var i in my_global_assoc_array)
console.log("cookie name = " + i + ", cookie value = " + i);
我对您问题的这一部分感到困惑:“棘手的部分是 cookie 值是动态创建的。” 由于 cookie 值只是 my_global_assoc_array 中的值,为什么您需要事先知道这些值是什么?
更新
如果您希望单个 cookie 包含 my_global_assoc_array 的所有值,则在 set cookie 例程中使用循环。像这样的东西:
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: '/'});
});