我有一个使用jQuery cookie插件设置的函数:https://github.com/carhartl/jquery-cookie,.grid-block
上的点击功能将每个data-hook
存储在一个数组中,将它们保存为cookie,然后这些选定的div可在/itin/your-itin/
页面上查看。以下是我设置的演示:http://nealfletcher.co.uk/itin/如果您点击.grid-block
div,这会将它们添加到您的行程中,然后当您导航到:http://nealfletcher.co.uk/itin/your-itin/时,只有这些div是可查看并作为cookie存储x个时间。这很好用,但是如果我再回来添加更多的div,这些存储为cookie,但是之前的那些被擦除,我想继续附加到数组,将其存储为cookie,然后当你导航到: http://nealfletcher.co.uk/itin/your-itin/它会显示您的所有选择,即使它们已单独添加。如果这有道理?
jQuery的:
$(window).load(function () {
var cfilter = [];
var $container = $('.block-wrap');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.grid-block',
animationEngine: 'best-available',
filter: '.grid-block',
masonry: {
columnWidth: 151
}
});
$(".grid-block").click(function () {
var thing = $(this).attr("data-hook");
var test = "." + thing;
cfilter.push(test);
$.removeCookie('listfilter', {
path: '/itin/your-itin/'
});
// We need to set the cookie only once
// it stays at the url for 7 days
$.cookie("listfilter", cfilter, {
expires: 365,
path: '/itin/your-itin/'
});
});
if ($.cookie("listfilter") !== 'null') {
// console log just for testing
console.log($.cookie());
$('.block-wrap').isotope({
filter: $.cookie("listfilter")
});
return false;
} else {
// !! this part could be refactored
// as you don't really need to check against the url
// when the cookie doesn't exist show all elements
$('.block-wrap').isotope({
filter: ''
});
}
});
});
任何建议都将不胜感激!
答案 0 :(得分:0)
将var cfilter = [];
更改为var cfilter = $.cookie("listfilter");
这样您就可以加载更改的cookie并添加到它而不是覆盖它。
更好的代码练习是在使用之前检查cookie是否存在,但是你得到了我的提示。
您在实施我的更改时出错:
if ($.cookie("listfilter") !== 'null') {
var cfilter = [];
} else {
var cfilter = $.cookie("listfilter");
}
错误,请使用
if ($.cookie("listfilter")) {
var cfilter = $.cookie("listfilter");
} else {
var cfilter =[];
}