向数组 cookie 添加值
Add values to array cookie
我需要向存储在cookie中的数组添加新变量。我该怎么做?
var arr = $.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]);
// this is an array of diferent numbers
function pri() { // this function create a number that is not in the array
var n = Math.floor((Math.random() * 15));
var tex;
while ((tex = $.inArray(n, arr)) != -1) {
n = Math.floor((Math.random() * 15));
}
return n;} //i need for whatever "n" is to be added to my array cookie
$.cookie 插件会将数组保存为字符串,如下所示:
var arr = $.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]);
返回请求,如下所示:
arr=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9
你必须首先保存数组,然后取回字符串并再次拆分它,然后你可以推送到它:
$.cookie("arr",[1, 2, 3, 4, 5, 6, 7, 8, 9]); // set the cookie
var arr = $.cookie("arr").split(','); // get the string and split it
arr.push(pri()); // then add whatever the function returns
现在您可以将修改后的数组保存回 cookie 中
$.cookie("arr", arr);
cookie 中的值只能是字符串,因此请使用(取消)序列化程序。
JSON在JavaScript中工作正常:
$.cookie("key", JSON.stringify([ 1, 2, 3]);
用法:
function add_value(new_value) {
var value = JSON.parse($.cookie("key")); // unserialize
value.push(new_value); // modify
$.cookie("key", JSON.stringify(value)); // serialize
}
相关文章:
- 单击时将类添加到 ancer 标签并使用 cookie 保存
- 添加/删除类并使用Cookie记住所选内容
- 在Protractor中添加Cookie以测试AngularJS
- 可以't从JSON在Phantomjs中添加cookie
- 添加Cookie以在jQuery移动页面中保持字体大小
- 向js fiddle添加cookie以保存用户键入的内容
- 如何在 Drupal7 中单击按钮时添加 cookie
- 在网页上加载闪光横幅后添加cookie
- 如何在java脚本中单击时添加cookie
- 无法通过iframe添加cookie
- jQuery,slideToggle-添加Cookie以记住状态
- 向10万用户添加cookie时需要考虑的性能问题
- 添加cookie以切换侧边栏
- Cookies html + js添加cookie不工作
- 如何在JMeter中修改/添加Cookie
- 添加cookie以拖放
- 为什么在请求远程脚本时添加cookie
- 在引导可折叠侧边栏导航中添加Cookie
- Javascript websocket客户端向报头添加cookie
- 在我的游戏中添加cookie