You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将选中的网站语言存储到localStorage,刷新页面后保留设置?

解决页面刷新后语言设置重置的问题

完全可以通过localStorage实现语言设置的持久化,刷新页面后依然保留用户选择的语言。只需要对现有JavaScript代码做以下修改:

修改后的JavaScript代码

const langEl = [...document.querySelectorAll(".lang")];
const textEl = document.querySelector(".text");

// 初始化时从localStorage读取,没有则用默认值
let chosenLanguage = localStorage.getItem('selectedLang') || 'NL';
let selectedLangKey = localStorage.getItem('selectedLangKey') || 'dutch';

// 页面加载时恢复语言状态
const initLanguage = () => {
  // 激活对应的语言按钮
  langEl.forEach(el => {
    if (el.innerText === chosenLanguage) {
      el.classList.add("active");
    } else {
      el.classList.remove("active");
    }
  });
  // 设置对应文本
  textEl.textContent = data[selectedLangKey].text;
};

// 语言切换事件
langEl.forEach((el) => {
  el.addEventListener("click", (e) => {
    e.preventDefault(); // 阻止a标签默认跳转行为
    // 移除所有active类
    langEl.forEach(item => item.classList.remove("active"));
    el.classList.add("active");
    
    chosenLanguage = el.innerText;
    const attr = el.getAttribute("language");
    selectedLangKey = attr;
    
    // 更新文本
    textEl.textContent = data[attr].text;
    
    // 存入localStorage
    localStorage.setItem('selectedLang', chosenLanguage);
    localStorage.setItem('selectedLangKey', attr);
  });
});

var data = {
  dutch: {
    text: "test test"
  },
  english: {
    text: "test test"
  },
  spanish: {
    text: "prueba prueba"
  },
  indonesian: {
    text: "tes tes"
  }
};

// 页面加载完成后初始化语言
document.addEventListener('DOMContentLoaded', initLanguage);

关键改动说明

  • 初始化读取存储:页面加载时优先从localStorage获取之前保存的语言设置,没有则使用默认的荷兰语(NL)
  • 持久化存储设置:用户切换语言时,将选中的语言显示文本和对应的属性值存入localStorage
  • 页面加载恢复状态:通过initLanguage函数,在页面加载完成后自动激活对应的语言按钮并设置对应文本
  • 阻止默认跳转:给a标签的点击事件添加e.preventDefault(),避免页面跳转导致的状态丢失

原HTML和CSS代码无需修改

HTML代码

<p class="text">test test</p>

<div class="language">
  <div class="langWrap">
    <a href="#" language='dutch' class="lang active">NL</a>
    <a href="#" language='english' class="lang">EN</a>
    <a href="#" language='spanish' class="lang">ES</a>
    <a href="#" language='indonesian' class="lang">ID</a>
  </div>
</div>

CSS代码

:root {
  --secondary-color: #4978ff;
}

.language {
  background: #141414;
  text-align: center;
  padding: 60px 0 50px;
}

.language a {
  margin: 0;
  text-transform: uppercase;
  color: #fff;
  text-decoration: none;
  padding: 0 15px;
  font-weight: bold;
  background: #555656;
  font-size: 18px;
}

.language a.active {
  background: var(--secondary-color);
}

内容的提问来源于stack exchange,提问作者Pascal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:17:14