我在主页面中使用了一个功能。一切正常,我只想知道当我点击链接并进入另一页时如何在页面中保留选择语言。
例如id =" en"默认情况下是语言,但如果我想使用id =" fr"在我的主页面中,点击链接,他将在另一页面发送给我。我会回到id =" en"。所以为了保持相同的语言,我该如何使用这个功能:
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
这是我用来切换语言的函数的jsfiddle:
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>
&#13;
答案 0 :(得分:0)
首先存储您的价值
$('.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
});
然后在.ready
函数
var langStored = localStorage.getItem("language");
如果没有存储值,它将返回null
。
因此,当您获得langStored
以及获得null
看一眼:codepen
答案 1 :(得分:0)
设置/获取localStorage项目。
localStorage.setItem('selectedLang', $(this).attr('id'));
localStorage.getItem('selectedLang');
您的示例代码
$(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'));
});
});