簡體   English   中英

jQuery:單擊添加到數組並另存為Cookie

[英]jQuery: click add to array and save as cookie

我有一個使用jQuery cookie插件設置的函數: https : //github.com/carhartl/jquery-cookie ,在.grid-block上具有click函數,它將每個data-hook存儲在一個數組中,並將它們保存為cookie ,則可以在/itin/your-itin/頁面上查看這些選定的div。 這也是我也建立的一個演示: http : .grid-block如果單擊.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: ''
            });
        }
    });

});

任何建議將不勝感激!

更改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 =[];
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM