【发布时间】:2014-02-11 05:48:02
【问题描述】:
如何在此脚本上保存所选项目以在刷新或更改页面后可用? (作为回答;JSFiddle 演示):Add/Remove Products to Compare with Jquery
编辑:
cookie 与会话相比,哪种做法更好?
我尝试使用 cookie。我将所有添加的项目(id 和图像)保存到一个 cookie 中,并且我只能删除所有选定的项目。如何从 cookie 中只删除一项?
代码:
$("#compareContainerFill").append($.cookie("newLi"));
$(".compare").click(function() {
var id=$(this).find('#compareID').text();
var image=$(this).find('#imageURL').text();
var selected = getSelectedIds();
if(selected.length == 4) return; // already 4 items added
if(selected.indexOf(id) != -1) return; // item already added
var newLi = $('<div/>', { 'class': 'box' })
.append($('<input type="hidden" value="'+id+'" name="compare_id['+id+']"/>'))
.append($('<span/>', { class: 'prod-id hidden', text: id }))
.append($('<a/>', { href: '#', text: '' }).append($('<img src="http://localhost/...imagelink">')))
.appendTo('#compareContainerFill');
$.cookie('newLi', (($.cookie("newLi") ? $.cookie("newLi") : '') + newLi.clone().wrap('<div />').parent().html()), { expires: 1 });
});
$("#compareContainerFill").live("click", function() {
$.removeCookie('newLi');
$('.box').remove();
});
【问题讨论】:
-
在 cookie 中存储选中项的列表,当页面加载时,检查 cookie 的值并将正确的对象设置为选中。
标签: javascript jquery session