我试图检测用户的语言设置,然后根据它重定向她。如果用户将pl
作为其默认语言设置,则应将其重定向到polish.html
。如果是ru
,那么russian.html
。否则,english.html
。
a = navigator.language;
b = navigator.userLanguage;
language = (a && !b)? a.toLowerCase() : b;
pl = 'pl';
ru = 'ru';
en = 'en'||'us'||'au'||'bz'||'ca'||'gb'||'ie'||'jm'||'nz'||'tt'||'za';
switch (language) {
case pl: window.location.replace('polish.html'); break;
case ru: window.location.replace('russian.html'); break;
case en: window.location.replace('english.html'); break;
}
通常,上述脚本有效,但有一个问题:浏览器不断刷新页面。我该如何解决这个问题?
答案 0 :(得分:1)
您的问题是您不断重新加载页面,无论您当前的状态如何。如果您的用户的语言是英语并且您在english.html
,则没有理由重新加载该页面。
var language = (navigator.language || navigator.userLanguage).toLowerCase(),
// simpler way of getting the user's language (take advantage of || in JS)
en = [ "en", "us", "au", "bz", "ca", "gb", "ie", "jm", "nz", "tt", "za" ],
// we'll need an array of the languages associated with English
currentPage = window.location.href.toLowerCase();
if (language == "pl" && currentPage.indexOf("polish") == -1) {
// if the user's language is polish and the page's link doesn't contain polish
// in it, redirect the user to polish.html
window.location.replace("polish.html");
} else if (language == "ru" && currentPage.indexOf("russian") == -1) {
// same concept as above
window.location.replace("russian.html");
} else if (en.indexOf(language) > -1 && currentPage.indexOf("english") == -1) {
// here, we're checking whether their language is in the array
// of user languages that should default to english
window.location.replace("english.html");
}
您甚至可以通过从上一个en.indexOf(language) > -1
语句中删除else if
来简化上述逻辑。这将成为默认目标网页english.html
。