如何删除cookie中的特定值 - jquery

时间:2014-03-13 06:25:53

标签: javascript jquery cookies

我正在开发一个购物车系统,用户可以在其中添加或移除产品。

我在产品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

1 个答案:

答案 0 :(得分:1)

尝试

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
        }
    }
}