如何在jquery中的cookie,会话或本地存储中存储和恢复数组特定时间

时间:2016-08-23 07:50:19

标签: javascript jquery cookies local-storage session-storage

如何在Cookie,会话或本地存储中存储阵列的内容,然后再次恢复或推入阵列以作为常规使用。它应该设置为特定时间,在此之后,它不应该恢复值。

修改 我试过这个需要本地存储和会话存储的cookie以及数组

var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

1 个答案:

答案 0 :(得分:2)

对于cookie:

 var date = new Date();
 var cars = ["Saab", "Volvo", "BMW"]; 
 date.setTime(date.getTime() + (30 * 60 * 1000)); //Expires in 30 minutes
 $.cookie("cookieName", cars, { expires: date });
 alert( $.cookie("cookieName") );

对于本地存储:

var cars = ["Saab", "Volvo", "BMW"]; 
localStorage.setItem( 'name', cars );
date.setTime(date.getTime() + (30 * 60 * 1000));
var date = new Date();
localStorage.setItem( 'expiretime', date );
if(localStorage.getItem( 'expiretime' ) > Date()) {
    alert(localStorage.getItem( 'name' ));
}

对于会话:

var cars = ["Saab", "Volvo", "BMW"]; 
$.session.set("name", cars);
date.setTime(date.getTime() + (30 * 60 * 1000));
var date = new Date();
$.session.set("expiretime", date);
if($.session.get( 'expiretime' ) > Date()) {
    alert($.session.get( 'name' ));
}