怎么使用javascript json保留语言

本教程将介绍如何使用javascript json保留语言的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么使用javascript json保留语言 教程 第1张

问题描述

我在main.js和index.html中使用以下代码来更改语言。在按下按钮后,它可以更改所有三种语言的内容。然而,每次用户更改页面时,该语言都会返回到"ENG"。有什么办法保留用户最后一次选择的语言?谢谢。

main.js

/* Lang.json newly added */
$.getJSON("Lang.json", function(json) {
 console.log(json); // this will show the info it in firebug console
});

$(document).ready(function() {
// The default language is English
  var lang = "ENG";
  $(".lang").each(function(index, element) {
 $(this).text(arrLang[lang][$(this).attr("key")]);
  });
});

// get/set the selected language
$(".translate").click(function() {
  var lang = $(this).attr("id");
  $(".lang").each(function(index, element) {
 $(this).text(arrLang[lang][$(this).attr("key")]);
  });
});

index.html

<button class="translate" id="ENG">
 <a style="cursor: pointer;"><img src="assets/img/eng.png" /></a> 
</button>
<button class="translate" id="CHT">
 <a style="cursor: pointer;"><img src="assets/img/cht.png" /></a>
</button>
<button class="translate" id="CHS">
 <a style="cursor: pointer;"><img src="assets/img/chs.png" /></a>
</button>

推荐答案

您可以使用本地存储来保留值。检查下面我已添加备注。

$(document).ready(function() {
// The default language is English
  // Get the lang value from localStorage, if not set use the default value 'ENG'
  var lang = window.localStorage.getItem('lang') || "ENG";
  $(".lang").each(function(index, element) {
 $(this).text(arrLang[lang][$(this).attr("key")]);
  });

// get/set the selected language
  $(".translate").click(function() {
 var lang = $(this).attr("id");
 // Save the lang value to localStorage to preserve
 window.localStorage.setItem('lang', lang);
 $(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
 });
  });
});

好了关于怎么使用javascript json保留语言的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。