Use localStorage.setItem to keep same show/hide divs

大兔子大兔子 提交于 2019-12-25 07:59:07

问题


I work with a function in my main page. All works fine, I just want to know how to keep the select language in a page when i click on a link and go in another page.

For example id="en" is the language by default, but if I want to use id="fr" in my main page, and click on link who will send me in another page. I will come back to id="en". So to keep the same language how can I use this function :

localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language"); 

Here is the jsfiddle of the function that I use to switch language:

https://jsfiddle.net/kodjoe/chvw181j/

$(document).ready(function() {
  $('.lan').hide();
  $('.en').show();
});

$('.button').click(function(event) {
  $('.lan').hide();
  var selectedLanguage = $(this).attr('id');
  var setActiveLanguage = "." + selectedLanguage;
  $(setActiveLanguage).show();

localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language"); 
});
.button {
  cursor: pointer;
  padding: 0px 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="button" id="en">EN</a>
<a class="button" id="fr">FR</a>
<a class="button" id="de">DE</a>


<div class="lan en">1</div>
<div class="lan fr">2</div>
<div class="lan de">3</div>
<div class="lan en">4</div>
<div class="lan fr">5</div>
<div class="lan de">6</div>

回答1:


firstly store your value

$('.button').click(function(event) {
  $('.lan').hide();
  var selectedLanguage = $(this).attr('id');
  var setActiveLanguage = "." + selectedLanguage;
  $(setActiveLanguage).show();

localStorage.setItem("language", selectedLanguage); //storing under the key of language

});

then fetch the value on ready in your .ready function

var langStored = localStorage.getItem("language");

if no values is stored it will return null.

So put conditions there what you want to do when you get langStored and when you get null

take a peek at: codepen




回答2:


Set / Get the localStorage item.

localStorage.setItem('selectedLang', $(this).attr('id'));

localStorage.getItem('selectedLang');

Documentation : HTML5 Web Storage

Code for your example

$(document).ready(function() {
    $('.lan').hide();
    var classSel = localStorage.getItem('selectedLang') ? localStorage.getItem('selectedLang') :  'en';
    //Get the value from localStorage and show that class only
    $('.'+classSel).show();

    $('.button').click(function(event) {
        $('.lan').hide();
        $("." + $(this).attr('id')).show();
        //Set the localStorage value
        localStorage.setItem('selectedLang', $(this).attr('id'));
    });
});


来源:https://stackoverflow.com/questions/39676522/use-localstorage-setitem-to-keep-same-show-hide-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!