用 AI 写了个自动根据浏览器语言跳转 url 的代码,问关于语言标签的问题。

310 天前
 CSGO
AI 给了这样的代码:

<script>
var lang = (navigator.language || navigator.userLanguage).toLowerCase();
switch (lang) {

case 'it':
window.location.href = 'it.html';
break;

case 'de':
window.location.href = 'de.html';
break;

case 'ja':
window.location.href = 'ja.html';
break;

case 'zh-cn':
window.location.href = 'zh-cn.html';
break;
case 'zh-tw':
window.location.href = 'zh-tc.html';
break;

case 'zh-hk':
window.location.href = 'zh-tc.html';
break;

default:
window.location.href = 'en.html'; // Default to English if no match found
}
</script>

我的疑问是,我通过 chrome 调试,选了 Tokyo ,它语言是 ja-JP ,那么这个 ja-JP 不会跳转 ja.html?
那么其他如 de-DE 也不会跳转 de.html ?那我岂不是还得收集全部的 de-XX 和 ja-XX 都写入这个代码?
547 次点击
所在节点    前端开发
2 条回复
AoEiuV020JP
310 天前
那就别用 switch , 用 if startsWith 之类的判断条件,或者干脆 split 分成两个部分分别判断,
CSGO
309 天前
@AoEiuV020JP OK

if (lang.startsWith('ja')) {
window.location.href = 'ja.html';
break;
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/994197

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX