Как переключить язык страницы с помощью JavaScript?

Опубликовано: 1 Декабря, 2021

В этой статье мы опишем метод переключения между языками страницы в зависимости от выбора пользователя.

Метод работает с использованием хеш-фрагмента URL-адреса в качестве идентификатора, который может быть использован позже, обнаруженный сценарием, для изменения языка. Доступ к хешу осуществляется с помощью свойства window.location.hash в JavaScript. и позже может быть проверен на предмет необходимого идентификатора языка.

Для этого подхода необходимо выполнить следующие шаги:

Шаг 1. Мы определяем функцию, которая принимает идентификатор языка как строку и устанавливает ее как хеш-фрагмент URL-адреса. Затем мы перезагрузим страницу с помощью метода location.reload ().

Шаг 2: Мы сохраняем все содержимое страницы в объекте, чтобы его можно было легко извлечь с помощью сценария в зависимости от языка.

Шаг 3: Затем мы проверим, совпадает ли текущее значение хеш-функции с языковым тегом, который мы хотим, и, следовательно, установим соответствующее содержимое языка из объекта, который мы определили выше.

HTML

// Create a function to change the hash
// value of the page and reload it
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;
}
}

Пример: этот пример демонстрирует вышеупомянутый подход, отображая три кнопки для выбора пользователем любого языка и изменяя язык при нажатии кнопки.

HTML

<!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 >

Выход: