localstorage刷新页面保存

时间:2019-11-13 11:44:27

标签: javascript jquery onclick local-storage

当我单击两个按钮时,已经设法将数据保存在本地存储中。我想更改页面上的语言,但是当我刷新时,它会恢复为默认值吗?为什么会这样?

$(function(){
    $(".translate").click(function(e){

        languages = e.target.value;
        $(localStorage.setItem("Language", languages));
        localStorage.getItem(arrLanguage);
    });
});

2 个答案:

答案 0 :(得分:0)

检查项目在本地存储中是否存在,是否使用过,是否未设置

$(function() {
  $(".translate").click(function(e) {
    if (typeof localStorage.getItem('Language') == 'string') {
      languages = localStorage.getItem('Language');
    } else {
      languages = e.target.value;
      $(localStorage.setItem("Language", languages));
    }
  });
});

答案 1 :(得分:0)

尝试实际使用它

var lang, defaultLanguage = "en_UK";
$(function(){
  $(".translate").click(function(e){
    var newlanguage = e.target.value;
    lang = localStorage.getItem("Language");
    if (lang && newlanguage && lang != newlanguage) { 
      $(localStorage.setItem("Language", newLanguage);
      location.reload():
    }
  });
  lang = localStorage.getItem("Language") || defaultLanguage;
  doSomethingToShowThePageInThisLanguage()
});