JavaScript 如何切换页面的语言
在本文中,我们将描述根据用户选择切换页面语言的方法。
该方法通过使用URL的哈希片段作为标识符,可以在脚本中使用后来检测到并改变语言。可以使用JavaScript中的 window.location.hash 属性访问哈希。
方法如下:
- 我们定义一个函数,将语言标识符作为字符串接受,并将其设置为URL的哈希片段。然后使用 location.reload() 方法重新加载页面。
- 我们将页面的所有内容存储在一个对象中,以便根据语言轻松检索脚本。
- 我们将检查当前的哈希值是否等于我们想要的语言标签,从而设置以上定义的对象中相应的语言内容。
示例:
<!DOCTYPE html>
<html>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
Click on the buttons below to change
the language of the webpage.
</p>
<!-- Define the buttons that will
change the language of the page
and reload it -->
<button onclick="changeLanguage('eng')">
Change to English<
/button>
<button onclick="changeLanguage('es')">
Change to Spanish
</button>
<button onclick="changeLanguage('hin')">
Change to Hindi
</button>
<!-- Define the content of the page
that would be changed -->
<p id="siteContent">
Welcome to the GeeksforGeeks Portal!
You can choose any language using the
buttons above!
</p>
<script>
// Create a function to change
// the hash value of the page
function changeLanguage(lang) {
location.hash = lang;
location.reload();
}
// Define the language reload anchors
var language = {
eng: {
welcome: "Welcome to the GeeksforGeeks " +
"Portal! You can choose any language " +
"using the buttons above!"
},
es: {
welcome: "¡Bienvenido al portal GeeksforGeeks! " +
"¡Puedes elegir cualquier idioma usando " +
"los botones de arriba!"
},
hin: {
welcome: "GeeksforGeeks पोर्टल पर आपका स्वागत है! " +
"आप ऊपर दिए गए बटन का उपयोग करके किसी भी " +
"भाषा को चुन सकते हैं!"
}
};
// Check if a hash value exists in the URL
if (window.location.hash) {
// Set the content of the webpage
// depending on the hash value
if (window.location.hash == "#es") {
siteContent.textContent =
language.es.welcome;
}
else if (window.location.hash == "#hin") {
siteContent.textContent =
language.hin.welcome;
}
}
</script>
</body>
</html>
HTML
输出: