web前端,多语言切换,data-localize,
demo:
链接:https://pan.baidu.com/s/1zhFHTv4P_epbBfpiggVDXg
提取码:aqts
要想有效果,必须发布在服务器上,可以在IIS上测试。
我只用到了中文和英文,想多语言的,就自己添加语言包
把select选择的语言也存在cookie中,刷新页面,也会记住选择
<select id="ddlSomoveLanguage" onchange="chgLang();"> <option value="zh">中文</option> <option value="en">ENGLISH</option> </select>
language_cookie.js
var name = "somoveLanguage"; /*server*/ var ctx = window.document.location.href.substring(0, window.document.location.href.indexOf(window.document.location.pathname)); function chgLang() { var value = $("#ddlSomoveLanguage").children('option:selected').val(); $('#ddlSomoveLanguage option:selected').text(); SetCookie(name, value); //location.reload(); } function SetCookie(name, value) { var Days = 30; //此 cookie 将被保存 30 天 var exp = new Date(); //new Date("December 31, 9998"); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() +";path=/"; } function getCookie(name)//取cookies函数 { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return unescape(arr[2]) } else { return null; } } var optionList = $("#ddlSomoveLanguage option"); var optionLength = optionList.length; // 画面加载的时候,执行方法 window.onload = function () { // 获得cookie,如果没有,默认为 zh var value = getCookie(name); value = value == undefined ? "zh" : value; for (var i = 0; i < optionLength; i++) { // 匹配 value,如果相同 value 则 selected 选中 if (optionList[i].value == value) { optionList[i].selected = "selected"; } } } //console.log(getCookie(name)); $(function () { var uulanguage = (navigator.language || navigator.browserLanguage).toLowerCase(); if (uulanguage.indexOf("en") > -1) { $("[data-localize]").localize("text", { pathPrefix: ctx + "/Content/lang", language: "en" }); } else if (uulanguage.indexOf("zh") > -1) { $("[data-localize]").localize("text", { pathPrefix: ctx + "/Content/lang", language: "zh" }); } else { $("[data-localize]").localize("text", { pathPrefix: ctx + "/Content/lang", language: "zh" }); }; if (getCookie(name) != "") { if (getCookie(name) == "zh") { $("[data-localize]").localize("text", { pathPrefix: ctx + "/Content/lang", language: "zh" }); } if (getCookie(name) == "en") { $("[data-localize]").localize("text", { pathPrefix: ctx + "/Content/lang", language: "en" }); } } });
本文来自博客园,作者:quitpoison,转载请注明原文链接:https://www.cnblogs.com/quitpoison/p/10183996.html