1

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

我正在尝试使用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');

我想将选择选项的值存储为 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}

4

1 回答 1

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');
})

在更正的小提琴中看到它。

于 2017-04-19T09:19:46.493 回答