您好,我有一个简单的应用程序,用户可以在英语和波兰语之间选择要在我的应用程序中使用的语言。
当用户打开我的网站时,这是我想要的行为:
- 如果浏览器语言 = 英语,则切换到波兰语。
- 如果浏览器语言 = 波兰语,则不执行任何操作。
- 假设波兰语是默认语言。
因为这是一个非常简单的应用程序,所以我使用 jQuery 进行翻译。
以下是我迄今为止的解决方案:
JSFIDDLE:demo
//redirect
$(document).ready(function() {
var userLang = navigator.language || navigator.userLanguage;
if (userLang == "pl-pl") {
break;
} else {
userLang = "eng-gb"
}
}
});
// translation
// The default language is Polish
var lang = "pl-pl";
// Check for localStorage support
if ('localStorage' in window) {
var usrLang = localStorage.getItem('uiLang');
if (usrLang) {
lang = usrLang
}
}
var arrLang = {
"pl-pl": {
"Valentine": "Do Walentynek zostało już tylko",
},
"en-gb": {
"valentine": "Remaining days to Valentines!",
}
}
$(document).ready(function() {
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
$(".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");
// update localStorage key
if ('localStorage' in window) {
localStorage.setItem('uiLang', lang);
}
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
});
<div class="translate">
<ul class="language">
<li class="eng translate" id="en-gb">EN</li>
<li class="pl translate" id="pl-pl">PL</li>
</ul>
</div>
<div class="rss-feed">
<p class="lang" key="valentine">Do Walentynek zostało już tylko
</p>
<span id="mybenfit-timer" class="lang" key="days">
</span>
</div>
不幸的是,我的解决方案不起作用。我的代码有什么问题吗?
最佳答案
尝试以下方法希望有帮助
$(document).ready(function() {
// translation
// The default language is English
var userLang = navigator.language || navigator.userLanguage;
var lang = "pl-pl";
// If Browser Language == English then switch to the Polish language.
// since there en-GB en-US ...
if(userLang.split('-')[0] == 'en'){
lang = "pl-pl";
}
// Check for localStorage support
if('localStorage' in window){
var usrLang = localStorage.getItem('uiLang');
if( typeof(usrLang) === 'string' && usrLang !== 'undefined') {
lang = usrLang
}
}
var arrLang = {
"pl-pl": {
"valentine": "Do Walentynek zostało już tylko",
"days": " 10 dni"
},
"en-gb": {
"valentine": "Remaining days to Valentines!",
"days": " 10 days"
}
}
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
// get/set the selected language
$(".translate").click(function(e) {
e.stopPropagation();
var lang = $(this).attr("id");
// update localStorage key
if('localStorage' in window){
localStorage.setItem('uiLang', lang);
}
$(".lang").each(function(index, element) {
$(this).text(arrLang[lang][$(this).attr("key")]);
});
});
});
关于javascript - 根据浏览器语言重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54244933/