实现多语言网站的页面间语言持久化:使用 localStorage 的前端解决方案

心靈之曲
发布: 2025-09-26 09:51:01
原创
874人浏览过

实现多语言网站的页面间语言持久化:使用 localstorage 的前端解决方案

本教程旨在解决多语言网站在页面切换时语言设置无法自动保存的问题。通过利用浏览器 localStorage 存储用户选择的语言偏好,并结合 JavaScript 在页面加载时动态应用该偏好,实现网站语言设置在不同页面间的无缝持久化,提升用户体验。

理解当前语言切换机制的局限性

在构建多语言网站时,一个常见的需求是用户选择的语言能够在不同页面间保持一致。然而,许多初学者在实现语言切换功能时,通常采用直接操作当前页面DOM(文档对象模型)的方式来更新文本内容。例如,通过 jQuery 的 .text() 方法来改变元素的显示文本,或通过 .addClass() / .removeClass() 来切换样式。

这种方法在单页应用(SPA)中可能表现良好,因为它只在当前页面执行。但对于传统的、多页面(MPA)的网站架构,每次页面跳转或刷新,浏览器都会重新加载页面资源,导致之前通过 JavaScript 对DOM进行的修改全部丢失。这意味着用户在一个页面选择了荷兰语,跳转到另一个页面时,网站又会恢复到默认语言,极大地损害了用户体验。

解决方案:利用 localStorage 实现语言持久化

为了解决语言设置在页面跳转后丢失的问题,我们需要一种机制来“记住”用户的语言选择。浏览器提供了多种客户端存储方案,其中 localStorage 是一个非常适合此场景的选择。

localStorage 是一种浏览器提供的 Web Storage API,它允许网站在用户浏览器中存储键值对数据,并且这些数据在浏览器关闭后依然保留,直到被用户清除或通过代码移除。这使得它成为保存用户偏好(如语言设置)的理想选择。

立即学习前端免费学习笔记(深入)”;

v1.7.3.3 PrestaShop开源电子商务
v1.7.3.3 PrestaShop开源电子商务

PrestaShop是一款针对web2.0设计的全功能、跨平台的免费开源电子商务解决方案,自08年1.0版本发布,短短两年时间,发展迅速,全球已超过四万家网店采用Prestashop进行布署。Prestashop基于Smarty引擎编程设计,模块化设计,扩展性强,能轻易实现多种语言,多种货币浏览交易,支持Paypal等几乎所有的支付手段,是外贸网站建站的佳选。Prestashop是目前为止,操作最

v1.7.3.3 PrestaShop开源电子商务 169
查看详情 v1.7.3.3 PrestaShop开源电子商务

其工作原理如下:

  1. 用户选择语言时:除了更新当前页面的DOM,我们将所选语言的标识符(例如 "en" 或 "nl")保存到 localStorage 中。
  2. 页面加载时:在每个页面加载时,JavaScript 代码会首先检查 localStorage 中是否存在已保存的语言标识符。
  3. 应用语言偏好:如果找到,则根据该标识符调用相应的语言切换函数,将页面内容设置为用户上次选择的语言。如果未找到,则应用默认语言。

实现步骤与示例代码

为了将 localStorage 集成到现有的语言切换逻辑中,我们需要对现有代码进行一些重构和扩展。

1. 重构语言切换逻辑为独立函数

首先,将针对每种语言的DOM操作封装成独立的函数。这有助于代码的组织性、可读性,并方便在不同场景下复用。

// 封装荷兰语切换逻辑
function setLanguageToNL() {
    // Language Select
    $(".language-selected").text("nl-NL").removeClass("change-en").addClass("change-nl");

    // Navbar
    $("#navbar-over-ons").text("Over Ons");
    $("#navbar-winkel").text("Winkel");
    $("#navbar-beoordelingen").text("Beoordelingen");
    $("#navbar-contact").text("Contact");
    $("#navbar-portfolio").text("Portfolio");
    $("#navbar-winkelwagen").text("Winkelwagen");

    // Footer
    $("#footer-diensten").text("Diensten");
    $("#footer-over").text("Over");
    $("#footer-overig").text("Overig");
    $("#footer-winkel").text("Winkel");
    $("#footer-over-ons").text("Over Ons");
    $("#footer-beoordelingen").text("Beoordelingen");
    $("#footer-contact").text("Contact");
    $("#footer-portfolio").text("Portfolio");
    $("#footer-changelog").text("Changelog");

    // Index
    $("#index-producten").text("Producten");
    $("#index-keuzes").text("U kunt kiezen uit deze 4 keuzes");
    $("#index-air-photo").text("Lucht Foto");
    $("#index-air-video").text("Lucht Video");
    $("#index-air-combination").text("Lucht Combinatie");
    $("#index-complete-package").text("Complete Pakket");
    $("#index-air-photo-paragraph").text("We maken meerdere foto's waaruit u kunt kiezen, in verschillende hoeken en hoogtes.");
    $("#index-air-video-paragraph").text("Wij maken een video in verschillende hoeken, hoogtes en bereik van uw wensen.");
    $("#index-air-combination-paragraph").text("Wij maken een combinatie van video's en foto's.");
    $("#index-complete-package-paragraph").text("Wij maken meerdere foto's en video's voor bijvoorbeeld bruiloften en zijn in te huren voor langere tijd.");
    $("#index-lees-verder").text("Lees Verder»");
    $("#index-faq").text("FAQ");
    $("#index-faq-v1").text("Als ik iets haal, Hoe kan ik dan betalen?");
    $("#index-faq-v2").text("Waar kan ik met vragen terecht?");
    $("#index-faq-v3").text("Als ik niet tevreden ben, kan ik dan een refund krijgen?");
    $("#index-faq-v4").text("Als ik iets haal kan ik dan annuleren?");
    $("#index-faq-v5").text("Wat als het slecht weer is, krijg ik dan regen foto's?");
    $("#index-faq-a1").text("U moet gelijk betalen via onze site tijdens het bestellen van een van onze diensten.");
    $("#index-faq-a2").text("U kunt ons contacteren via het kopje 'Contact' Op onze site voor enige vragen over onze diensten.");
    $("#index-faq-a3").text("U kan geen refund krijgen, We kunnen u wel korting geven op uw volgende bestelling bij Prof Sky Shot.");
    $("#index-faq-a4").text("U kan uw dienst annuleren, U moet dit dan wel 24 uur van te voren doen. Of u kan een andere tijd afspreken met onze medewerkers, Dit moet wel 24 uur van te voren gedaan worden. Dit kan allemaal gedaan worden via onze 'Contact'  pagina op onze site.");
    $("#index-faq-a5").text("Met slecht weer word er een andere tijd afgesproken met u en onze medewerkers, Tenzij het een van onze speciale diensten zijn zoals de 'Complete Package'. Dan gaan we verder in de regen.");

    // Changelog
    $("#website-changelog").text("Website Changelog");
    $("#changelog-pagina").text("Pagina");
    $("#changelog-tijd").text("Tijd");
    $("#changelog-toegevoegt").text("Toegevoegt");
    $("#changelog-Bug-Fix").text("Bug-Fix");
    $("#changelog-aangepast-toegevoegt").text("Aangepast-Toegevoegt");
    $("#changelog-item-pagina").text("Changelog Pagina");
    $("#niet-klaar-popup").text("Niet Klaar Popup");
    $("#aparthotel-las-mariposas-features-lees-meer-knop").text("Aparthotel Las Mariposas Features Lees Meer Knop");
    $("#pagina-kopje").text("Pagina Kopje");

    // 404
    $("#404-pagina-niet-gevonden").text("Pagina niet gevonden!");
    $("#404-pagina-niet-gevonden-paragraph").text("Deze pagina is niet gevonden, druk op de knop hieronder om terug te gaan naar de vorige pagina.");
    $("#404-ga-terug").text("Ga Terug!");

    // Aparthotel Las Mariposas
    $("#aparthotel-las-mariposas-features").text("Features");
    $("#aparthotel-las-mariposas-features-klik-hier").text("Klik Hier");
    $("#aparthotel-las-mariposas-apparatuur").text("Apparatuur");
    $("#aparthotel-las-mariposas-locatie").text("Locatie");
    $("#aparthotel-las-mariposas-contact").text("Contact");
    $("#aparthotel-las-mariposas-over-ons").text("Over Ons");
    $("#aparthotel-las-mariposas-apparatuur-paragraph").text("Elke appartement is in bezit van een: Kluis, Koelkast, Magnetron, Broodrooster, Waterkoker, Eigen badkamer, Nieuwe matras, 90X200 Bedden, Terras met tafel met stoelen, Satelliet/Kleuren TV, Eettafel en stoelen, Volledig ingerichte kitchenette, Bed- en badlinnen aanwezig, Comfortabel loungemeubilair.");
    $("#aparthotel-las-mariposas-locatie-paragraph").text("Het hotel zit dichtbij het strand, er zit een tankstation dichtbij, een ziekenhuis een paar restaurants en een paar winkels.");
    $("#aparthotel-las-mariposas-contact-paragraph").text("U kunt ons contacteren op het Telefoon Nummer:");
    $("#aparthotel-las-mariposas-contact-paragraph-email").text("Of E-Mail Adres:");

    // Cancel
    $("#cancel-betaling-mislukt").text("Betaling Mislukt!");
    $("#cancel-betaling-komt-niet-door").text("De betaling kon niet door komen, neem a.u.b. contact met ons op!");

    // Contact
    $("#contact-contacteer-ons").text("Contacteer Ons");
    $("#contact-faq").text("FAQ");
    $("#contact-faq-v1").text("Als ik iets haal, Hoe kan ik dan betalen?");
    $("#contact-faq-v2").text("Waar kan ik met vragen terecht?");
    $("#contact-faq-v3").text("Als ik niet tevreden ben, kan ik dan een refund krijgen?");
    $("#contact-faq-v4").text("Als ik iets haal kan ik dan annuleren?");
    $("#contact-faq-v5").text("Wat als het slecht weer is, krijg ik dan regen foto's?");
    $("#contact-faq-a1").text("U moet gelijk betalen via onze site tijdens het bestellen van een van onze diensten.");
    $("#contact-faq-a2").text("U kunt ons contacteren via het kopje 'Contact' Op onze site voor enige vragen over onze diensten.");
    $("#contact-faq-a3").text("U kan geen refund krijgen, We kunnen u wel korting geven op uw volgende bestelling bij Prof Sky Shot.");
    $("#contact-faq-a4").text("U kan uw dienst annuleren, U moet dit dan wel 24 uur van te voren doen. Of u kan een andere tijd afspreken met onze medewerkers, Dit moet wel 24 uur van te voren gedaan worden. Dit kan allemaal gedaan worden via onze 'Contact'  pagina op onze site.");
    $("#contact-faq-a5").text("Met slecht weer word er een andere tijd afgesproken met u en onze medewerkers, Tenzij het een van onze speciale diensten zijn zoals de 'Complete Package'. Dan gaan we verder in de regen.");

    // Order ID Template
    $("#order-order-id").text("Order#ID");
    $("#order-order-id-paragraph").text("Hier kunt u uw foto's en video's downloaden");
    $("#order-disclaimer").text("DISCLAIMER: Alles word na 48 uur verwijdert!");

    // Order Status
    $("#orderstatus-order-details").text("Uw Bestellings Gegevens!");

    // Over Ons
    $("#over-ons-ons-bedrijf").text("Ons Bedrijf");
    $("#over-ons-ons-bedrijf-paragraph").text("Wij zijn een startend bedrijf, ik heb zelf een passie voor het vliegen met drones en fotografie, toen ik op vakantie was kon ik de omgeving van het hotel waar ik heen ging niet vinden en daarom kwam ik op het idee om dit bedrijf te starten. Ik zou graag hun belangrijke momenten voor mensen vastleggen en zelf wat zakgeld verdienen, ik heb net een dronepilootlicentie gekregen om legaal te kunnen vliegen, ik heb ook een kamer van koophandel gekocht. We gebruiken een professionele drone, we maken foto's en video's in 4K-kwaliteit, we hebben een zeer groot vlieggebied zodat we zeer mooie omgevingsfilms kunnen maken, zonder schokken en schieten met een zeer goede beeldkwaliteit.");

    // Portfolio
    $("#portfolio-onze-portfolio").text("Onze Portfolio");
    $("#portfolio-onze-portfolio-paragraph").text("Dit is onze portfolio");

    // Reviews
    $("#beoordelingen-beoordelingen").text("Beoordelingen");
    $("#beoordelingen-nog-geen-informatie").text("Nog Geen Informatie");
    $("#beoordelingen-niemand").text("NIEMAND");
    $("#beoordelingen-beoordelingen-paragraph").text("Lees hier want onze klanten over ons vinden.");
    $("#beoordelingen-niemand-paragraph").text("NIEMAND");

    // Success
    $("#success-bedankt").text("Bedankt voor uw bestelling!");
    $("#success-bedankt-paragraph").text("Check A.U.B uw mailbox voor uw bestelling confirmatie!");
}

// 封装英语切换逻辑
function setLanguageToEN() {
    // Language Select
    $(".language-selected").text("en-US").removeClass("change-nl").addClass("change-en");

    // Navbar
    $("#navbar-over-ons").text("About Us");
    $("#navbar-winkel").text("Store");
    $("#navbar-beoordelingen").text("Reviews");
    $("#navbar-contact").text("Contact");
    $("#navbar-portfolio").text("Portfolio");
    $("#navbar-winkelwagen").text("Cart");

    // Footer
    $("#footer-diensten").text("Services");
    $("#footer-over").text("About");
    $("#footer-overig").text("Other");
    $("#footer-winkel").text("Store");
    $("#footer-over-ons").text("About Us");
    $("#footer-beoordelingen").text("Reviews");
    $("#footer-contact").text("Contact");
    $("#footer-portfolio").text("Portfolio");
    $("#footer-changelog").text("Changelog");

    // Index
    $("#index-producten").text("Products");
    $("#index-keuzes").text("You can choose from these 4 choices");
    $("#index-air-photo").text("Air Photo");
    $("#index-air-video").text("Air Video");
    $("#index-air-combination").text("Air Combination");
    $("#index-complete-package").text("Complete Package");
    $("#index-air-photo-paragraph").text("We take multiple photos for you to choose from, at different angles and heights.");
    $("#index-air-video-paragraph").text("We make a video in different angles, heights and range of your wishes.");
    $("#index-air-combination-paragraph").text("We make a combination of videos and photos.");
    $("#index-complete-package-paragraph").text("We take several photos and videos for, for example, weddings and can be hired for a longer period of time.");
    $("#index-lees-verder").text("Read More»");
    $("#index-faq").text("FAQ");
    $("#index-faq-v1").text("If I get something, how can I pay?");
    $("#index-faq-v2").text("Where can I go with questions?");
    $("#index-faq-v3").text("If I am not satisfied, can I get a refund?");
    $("#index-faq-v4").text("Can I cancel if I get something?");
    $("#index-faq-v5").text("What if the weather is bad, will I get rain photos?");
    $("#index-faq-a1").text("You must pay directly through our site when ordering one of our services.");
    $("#index-faq-a2").text("You can contact us via the 'Contact' section on our site for any questions about our services.");
    $("#index-faq-a3").text("You cannot get a refund, but we can give you a discount on your next order at Prof Sky Shot.");
    $("#index-faq-a4").text("You can cancel your service, you must do this 24 hours in advance. Or you can arrange a different time with our employees. This must be done 24 hours in advance. This can all be done through our 'Contact' page on our site.");
    $("#index-faq-a5").text("In bad weather, a different time will be agreed with you and our employees, unless it is one of our special services such as the 'Complete Package'. Then we continue in the rain.");

    // Changelog
    $("#website-changelog").text("Website Changelog");
    $("#changelog-pagina").text("Page");
    $("#changelog-tijd").text("Time");
    $("#changelog-toegevoegt").text("Added");
    $("#changelog-Bug-Fix").text("Bug-Fix");
    $("#changelog-aangepast-toegevoegt").text("Changed-Added");
    $("#changelog-item-pagina").text("Changelog Page");
    $("#niet-klaar-popup").text("Not Finished Popup");
    $("#aparthotel-las-mariposas-features-lees-meer-knop").text("Aparthotel Las Mariposas Features Read More Button");
    $("#pagina-kopje").text("Pagina Header");

    // 404
    $("#404-pagina-niet-gevonden").text("Page not found!");
    $("#404-pagina-niet-gevonden-paragraph").text("This page was not found, press the button below to go back to the previous page.");
    $("#404-ga-terug").text("Go Back!");

    // Aparthotel Las Mariposas
    $("#aparthotel-las-mariposas-features").text("Features");
    $("#aparthotel-las-mariposas-features-klik-hier").text("Click Here");
    $("#aparthotel-las-mariposas-apparatuur").text("Equipment");
    $("#aparthotel-las-mariposas-locatie").text("Location");
    $("#aparthotel-las-mariposas-contact").text("Contact");
    $("#aparthotel-las-mariposas-over-ons").text("About Us");
    $("#aparthotel-las-mariposas-apparatuur-paragraph").text("Each apartment has a: Safe, Fridge, Microwave, Toaster, Kettle, Private bathroom, New mattress, 90X200 Beds, Terrace with table with chairs, Satellite / Color TV, Dining table and chairs, Fully equipped kitchenette, Bed and bath linen present, Comfortable lounge furniture.");
    $("#aparthotel-las-mariposas-locatie-paragraph").text("The hotel is close to the beach, there is a gas station nearby, a hospital, a few restaurants and a few shops.");
    $("#aparthotel-las-mariposas-contact-paragraph").text("You can contact us at the Phone Number:");
    $("#aparthotel-las-mariposas-contact-paragraph-email").text("Or E-mail Address:");

    // Cancel
    $("#cancel-betaling-mislukt").text("Payment Failed!");
    $("#cancel-betaling-komt-niet-door").text("The payment could not go through, please contact us!");

    // Contact
    $("#contact-contacteer-ons").text("Contact Us");
    $("#contact-faq").text("FAQ");
    $("#contact-faq-v1").text("If I get something, how can I pay?");
    $("#contact-faq-v2").text("Where can I go with questions?");
    $("#contact-faq-v3").text("If I am not satisfied, can I get a refund?");
    $("#contact-faq-v4").text("Can I cancel if I get something?");
    $("#contact-faq-v5").text("What if the weather is bad, will I get rain photos?");
    $("#contact-faq-a1").text("You must pay directly through our site when ordering one of our services.");
    $("#contact-faq-a2").text("You can contact us via the 'Contact' section on our site for any questions about our services.");
    $("#contact-faq-a3").text("You cannot get a refund, but we can give you a discount on your next order at Prof Sky Shot.");
    $("#contact-faq-a4").text("You can cancel your service, you must do this 24 hours in advance. Or you can arrange a different time
登录后复制

以上就是实现多语言网站的页面间语言持久化:使用 localStorage 的前端解决方案的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号