如何实现点击翻译状态跨页面生效、页面刷新不重置?
实现方案
核心通过本地存储持久化用户的语言选择,同时在每个页面加载时自动读取状态执行翻译,无需用户重复点击按钮,具体实现如下:
改造后的完整代码
HTML 部分
<button class="translate" type="button" id="translateBtn">FR</button> <p id="servicesIntro"><span class="firstWord">We</span> offer many additional services for your cat, when you book with us you can choose from any of the options below. If needed any adjustments made to our prices will be discussed once an appointment is made. Any other questions or concerns can be discussed with us when you book an appointment. Feel free to call, e-mail us or even contact us through our social media during our work hours from 9 A.M to 6 P.M Tuesday to Saturday. </p>
JS 部分
// 翻译映射表,后续新增文本/语言直接在这里扩展即可 const translateMap = { 'servicesIntro': { en: '<span class="firstWord">We</span> offer many additional services for your cat, when you book with us you can choose from any of the options below. If needed any adjustments made to our prices will be discussed once an appointment is made. Any other questions or concerns can be discussed with us when you book an appointment. Feel free to call, e-mail us or even contact us through our social media during our work hours from 9 A.M to 6 P.M Tuesday to Saturday.', fr: '<span class="firstWord">Nous</span> proposons de nombreux services supplémentaires pour votre chat. Lorsque vous réservez avec nous, vous pouvez choisir parmi l\'une des options ci-dessous. Si nécessaire, tout ajustement apporté à nos prix sera discuté une fois le rendez-vous pris. Toute autre question ou préoccupation peut être discutée avec nous lorsque vous prenez rendez-vous. N\'hésitez pas à nous appeler, nous envoyer un e-mail ou même nous contacter via nos réseaux sociaux pendant nos heures de travail de 9h à 18h du mardi au samedi.' } // 其他需要翻译的元素ID,按照上面的格式添加即可 } const translateBtn = document.getElementById('translateBtn') // 执行翻译的公共函数 function switchLang(lang) { // 存储语言选择到用户本地,同域名下所有页面共享 localStorage.setItem('siteLang', lang) // 遍历映射表替换所有对应文本 Object.keys(translateMap).forEach(id => { const el = document.getElementById(id) if (el && translateMap[id][lang]) { el.innerHTML = translateMap[id][lang] } }) // 切换按钮显示文本,支持来回切换语言 translateBtn.innerText = lang === 'en' ? 'FR' : 'EN' } // 绑定按钮点击事件 translateBtn.addEventListener('click', () => { const currentLang = localStorage.getItem('siteLang') || 'en' const targetLang = currentLang === 'en' ? 'fr' : 'en' switchLang(targetLang) }) // 页面加载时自动读取存储的语言状态,自动执行翻译 document.addEventListener('DOMContentLoaded', () => { const savedLang = localStorage.getItem('siteLang') if (savedLang && savedLang !== 'en') { switchLang(savedLang) } })
跨页面适配方法
- 所有站点页面都引入上述JS代码,保持翻译按钮的ID为
translateBtn不变 - 其他页面需要翻译的元素,把对应ID和英法文本添加到
translateMap映射表中即可 - 本地存储的
siteLang变量同域名下全站共享,跳转页面、刷新浏览器都不会丢失状态
内容的提问来源于stack exchange,提问作者gears244
相关产品推荐
相关产品推荐

