如何删除cookie中的特定值- jquery
How to delete a specific value in a cookie - jquery
我正在开发一个购物车系统,用户可以在其中添加或删除产品到他或她的购物篮。
我在产品cookie中为每个产品存储2个东西:产品条形码和价格。
到目前为止,我的代码是这样的:var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");
var Basket = {
select: function (box, cookie) {
box.addClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9'.]/g, '');
if ($.cookie(cookie) == undefined) {
$.cookie(cookie, ean + "~" + value);
} else if ($.cookie(cookie).indexOf(ean) == -1) {
$.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
}
},
deselect: function (box, cookie) {
box.removeClass("selected");
// code to delete the cookie value
}
};
$(document).ready(function () {
$(addToBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.select(box, "productCookie");
});
$(removeFromBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.deselect(box, "productCookie");
});
});
添加3个产品到购物车后,我的cookie看起来是这样的:
productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30
请帮助我如何从上面的cookie列表中只删除选定的产品。
仅供参考,我使用jquery + jquery cookie
Try
deselect: function (box, cookie) {
box.removeClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9'.]/g, '');
var val = ean + "~" + value; //value to be removed
if ($.cookie(cookie) !== undefined) {
var cookie_val = $.cookie(cookie);
if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
var index = arr.indexOf(val);//get index of value to be deleted
arr.splice(index, 1); //remove value from array
$.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
}
}
}
相关文章:
- 使用jquery cookie的第三方cookie
- Jquery cookie - toggle box
- 如何使用 jquery.cookie 创建 if 语句
- 基于 jQuery Cookie 打开和关闭面板
- jquery cookie,在清除浏览器历史记录后仍然设置
- 为什么jQuery.cookie插件返回“[object object]”
- jQuery可以't使用jquery.cookie插件读取cookie
- jQuery cookie is not expring
- 正在保存CSS State Jquery Cookie
- 如何使用jquery cookie插件保存toggleClass方法的状态
- JQuery Cookie在1分钟后过期
- JQuery Cookie 不起作用
- jQuery Cookie 插件许可证
- jquery cookie 通过循环追加值
- JQuery cookie 在其他函数中设置
- 使用函数setTimerOut和jquery Cookie的模型窗口
- jQuery Cookie插件保存选择值
- jquery cookie for jquery animate
- 为什么这个 JQuery Cookie 值没有更新
- 将对象/数组存储在 jQuery Cookie 中