简体   繁体   中英

How to set a variable as Cookie (javascript)

I have translated a website and I want to remember which country a customer has selected. This is my code:

 $('.set_nl').click(function(){
   var translator = $('body').translate({lang: "nl", t: dict}); 
 });

 $('.set_de').click(function(){
   var translator = $('body').translate({lang: "de", t: dict}); 
 });

 $('.set_en').click(function(){ 
   var translator = $('body').translate({lang: "en", t: dict}); 
 });

How can I achieve this with cookies?

要存储cookie,您必须设置一个名称并将其保存为某种模式:

document.cookie = "username=John Doe";

Firstly to set a cookie using Javascript you can use the code outlined in this question , or as you have already included jQuery in the page you can use the $.cookie library .

From there you can set the value when a choice is made, then retrieve the value on load of the page to set the language the user previously set.

Also note that you can DRY up the multiple click handlers on the button which set the language by using a data attribute. Try this:

$('.lang').click(function() {
  var lang = $(this).data('lang');
  var translator = $('body').translate({
    lang: lang,
    t: dict
  });
  $.cookie('lang', lang);
});

// on load
$('body').translate({
  lang: $.cookie('lang'),
  t: dict
});
<a href="#" class="lang" data-lang="nl">NL</a>
<a href="#" class="lang" data-lang="de">DE</a>
<a href="#" class="lang" data-lang="en">EN</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM