jQuery - 从选择菜单中设置和检索cookie

时间:2017-04-19 09:00:34

标签: jquery select cookies js-cookie

我有一个选择菜单,可让您选择首选的送货国家/地区。当您选择一个选项时,它会显示相关的国家/地区。

我正在尝试使用js-cookie设置Cookie,以便始终记住用户的最后一个选择。这是我到目前为止所做的,但它只是不起作用:

https://jsfiddle.net/33xfzvg8/11/

$('#country').change(function() {
  $('.box').hide();
  var $countrycode = $('#delivery' + $(this).val());
  if( Cookies !== undefined && Cookies.get('deliveryOption') == undefined  ){
    Cookies.set('deliveryOption', $countrycode);
  } else {
    $('#delivery' + $(this).val()).show();
  }
}).trigger('change');

我想将select选项的值存储为cookie,然后使用相同的值来显示各自的国家/地区信息。这是当前存储的cookie,看起来不正确:

{%220%22:{%22jQuery112405649891521717818%22:9}%2C%22length%22:1%2C%22context%22:{%22location%22:{%22href%22:%22https://zed-labz.myshopify.com/pages/delivery%22%2C%22ancestorOrigins%22:{}%2C%22origin%22:%22https://zed-labz.myshopify.com%22%2C%22protocol%22:%22https:%22%2C%22host%22:%22zed-labz.myshopify.com%22%2C%22hostname%22:%22zed-labz.myshopify.com%22%2C%22port%22:%22%22%2C%22pathname%22:%22/pages/delivery%22%2C%22search%22:%22%22%2C%22hash%22:%22%22}%2C%22mc-embedded-subscribe-form%22:{%220%22:{}%2C%221%22:{}}}%2C%22selector%22:%22#deliverycountry1%22}

1 个答案:

答案 0 :(得分:1)

一些问题:

  • 您保存了jQuery集合,因为 $ countrycode 不是值:

    var $countrycode = $('#delivery' + $(this).val());
    
  • 从来没有从cookie中获取值来设置选择

以下是更正后的代码:

$(function () {
    $('#country').change(function() {
        $('.box').hide();
        if( Cookies ) {
            Cookies.set('deliveryOption', $(this).val());
        }
        $('#delivery' + $(this).val()).show().siblings().hide();
    });
    // On page load, read out the cookie, and select the corresponding country
    // If no cookie, take country1 as default
    var country = Cookies && Cookies.get('deliveryOption') || 'country1';
    $('#country').val(country).trigger('change');
})

the corrected fiddle中查看。