1

Есть такой простой скрипт и библиотека cookie. Как сделать,чтобы скрипт запоминал, какой язык был выбран даже после перезагрузки или перехода на другую страницу сайта?

	$(function(){
	$("#en-sw").click(function(){
   	jQuery('#fr-sw').removeClass("active");
   	jQuery('#en-sw').addClass("active");	
	jQuery('.fr').hide();	
	jQuery('.en').show();		
	
  });
  
  $("#fr-sw").click(function(){
   	jQuery('#en-sw').removeClass("active");
   	jQuery('#fr-sw').addClass("active");	
	jQuery('.en').hide();	
	jQuery('.fr').show();		
	
  });
 });


/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD (Register as an anonymous module)
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		module.exports = factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}

		try {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			// If we can't parse the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}

	var config = $.cookie = function (key, value, options) {

		// Write

		if (arguments.length > 1 && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
			}

			return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// Read

		var result = key ? undefined : {},
			// To prevent the for loop in the first place assign an empty array
			// in case there are no cookies at all. Also prevents odd result when
			// calling $.cookie().
			cookies = document.cookie ? document.cookie.split('; ') : [],
			i = 0,
			l = cookies.length;

		for (; i < l; i++) {
			var parts = cookies[i].split('='),
				name = decode(parts.shift()),
				cookie = parts.join('=');

			if (key === name) {
				// If second argument (value) is a function it's a converter...
				result = read(cookie, value);
				break;
			}

			// Prevent storing a cookie that we couldn't decode.
			if (!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		// Must not alter options, thus extending a fresh object...
		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
		return !$.cookie(key);
	};

}));
#fr-sw.active {font-weight:bold}
#en-sw.active {font-weight:bold}
.fr {display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<a id="en-sw" class="active">Eng</a>
<a id="fr-sw">Fr</a>

<div class="en">на Английском</div>
<div class="fr" style="display:none;">на Французском</div>

1 ответ 1

2

Я бы рекомендовал не использовать плагин для хранения данных на клиенте, вместо этого использовать localStorage. Вот пример кода:

  $(function() {
      var choosenLang = localStorage.getItem('lang') || 'fr';
      $('#' + choosenLang + '-sw').addClass('active');
      $('.' + choosenLang).show();
      $('.lang').on('click', function () {
          $('.active').removeClass('active');
          $(this).addClass('active');
          var lang = $(this).data('lang');
          $('.lang-div').hide();
          $('.' + lang).show();
         localStorage.setItem('lang', lang);
      });
  });
   #fr-sw.active {font-weight:bold}
   #en-sw.active {font-weight:bold}
   .fr, .en {display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="en-sw" class="lang" data-lang="en">Eng</a>
  <a id="fr-sw" class="lang"  data-lang="fr">Fr</a>

  <div class="en lang-div">на Английском</div>
  <div class="fr lang-div">на Французском</div>

3
  • Хм, ваш пример не работает на сайте. Т.е. он переключает,но не запоминает выбор. И по умолчанию французский активен
    – Artem G
    10 янв 2019 в 12:10
  • 1
    я немного исправил код, должно работать так как должно
    – Vladimir
    10 янв 2019 в 12:25
  • Супер! Теперь работает! Спасибо огромное!
    – Artem G
    10 янв 2019 в 12:40

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.