在Windows本地存储中存储所选语言

我使用i18Next来本地化HTML,并且我正在尝试缓存所选的语言,以便它在页面刷新时不会后退,但无法使其工作。 以下是我的代码。

<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>

<script>
    function updateContent() {
      const elements = document.getElementsByClassName("i18nelement");
      for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        const k = element.getAttribute("data-i18n");
        element.innerHTML = i18next.t(k);
      }
    }
    
    async function i18Loader() {
      const langs = ["en", "ru"];
      const jsons = await Promise.all(
        langs.map((l) => fetch("src/i18/" + l + ".json").then((r) => r.json()))
      );
      const res = langs.reduce((acc, l, idx) => {
        acc[l] = { translation: jsons[idx] };
        return acc;
      }, {});

      await i18next.init({
        lng: 'en',
        debug: true,
        resources: res,
        fallbackLng: "en-US"
      });
      updateContent();
      i18next.on("languageChanged", () => {
        updateContent();
      });
      const langSelector = document.getElementById("langSelector");
      langSelector.removeAttribute("disabled");
      langSelector.addEventListener("change", (e) => {
        i18next.changeLanguage(e.target.value);
      });
    }
    
    i18Loader();
</script>

如何在本地存储中存储所选语言?


解决方案

我找到了解决方案。此处的正确代码

async function i18Loader() {
  const langs = ["en", "ru"];
  const jsons = await Promise.all(
    langs.map((l) => fetch("src/i18/" + l + ".json").then((r) => r.json()))
  );
  const res = langs.reduce((acc, l, idx) => {
    acc[l] = { translation: jsons[idx] };
    return acc;
  }, {});

  await i18next

    .init({
      lng: localStorage.getItem("lan") || 'en',
      debug: true,
      resources: res,
      fallbackLng: "en-US",
      backend: {
        backendOptions: [{
          // can be either window.localStorage or window.sessionStorage. Default: window.localStorage
          store: typeof window !== 'undefined' ? window.localStorage : null
        }, {
          loadPath: '/scr/i18/{{lng}}.json' // xhr load path for my own fallback
        }]
      }
    });

  function updateContent() {
    const elements = document.getElementsByClassName("i18nelement");
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      const k = element.getAttribute("data-i18n");
      element.innerHTML = i18next.t(k);
    }
  }

  updateContent();
  i18next.on("languageChanged", () => {
    updateContent();
  });

  const langSelector = document.getElementById("langSelector");
  langSelector.removeAttribute("disabled");
  langSelector.addEventListener("change", (e) => {
    i18next.changeLanguage(e.target.value);
    localStorage.setItem("lan", e.target.value);
  });

}

i18Loader();

相关文章