this is my sample code
var myCookie;
var initial_arr = new Array();
var myCookie_arr = new Array();
var cookieItem;
$(fu开发者_运维技巧nction() {
...
/* This quite works but can't actually achieve what I want */
$('#add_item').click(function(){
initial_arr.push(msg.txt);
//Update new cookie
$.cookie('cookieItem', initial_arr, { expires: 1});
//append on click
$('#item-list').append(msg.txt);
});
/* This is what I intend to do */
//Update new cookie
$.cookie('cookieItem', msg.txt, { expires: 1});
// add elements at the end of my cookie array
myCookie_arr.push($.cookie('cookieItem'));
...
$(window).load(function() {
...
alert(myCookie_arr);
for(var i= 0; i < myCookie_arr; i++) {
//append on visiting other pages
$('#item-list').append(myCookie_arr[i]);
}
...
if(cookieItem) {
$('#item-list').append($.cookie('cookieItem'));
} else {
$('#cat').hide();
}
});
});
I saw your other question here and it appears you want to add, remove or clear the cookie array. I put these basic functions together to give you an idea of how to do that
function addToCookie(arr,item){
arr.push(item)
$.cookie('cookieItem', arr, {expires: 1});
// add item to cart
return arr;
}
function removeFromCookie(arr,item){
arr.splice( arr.indexOf(item) , 1);
$.cookie('cookieItem', arr, {expires: 1});
// remove item from cart
return arr;
}
function clearCookie(arr){
$.cookie('cookieItem', null );
// empty the cart
return [];
}
I strongly recommend you to forget the shopping cart cookie at all. Use ajax calls to maintain the shopping cart in the session at server side. Despite the specification, the cookie value has in the most webbrowsers namely not an unlimited length.
精彩评论