首页 > 解决方案 > 带有功能的Javascript本地存储?

问题描述

我有一个翻译功能,只需单击一个按钮,就可以使用 javascript 将段落从英文切换到法文。现在我使用 innerhtml 手动抓取预翻译的段落。我想使用 localStorage 存储用户操作。如果他们点击翻译 onclick 事件,它应该自动在每个其他页面上运行 translate_fr 函数。我想避免让用户每次加载新页面时都必须重新翻译网站。

我不知道如何使用某种条件语句执行此操作在浏览器中使用本地存储。

 function translate_fr(){
 
 document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème`;
 
}
<button class="translate" type="button" onclick="translate_fr()">FR</button>

    <p id="intro">
      Here at Lion Kuts we are a cat only
      establishment that offers a full range of services 
      from complete grooming, bathing to boarding. You and 
      your pet will be thrilled to know that only professional, 
      natural and biodegradeable products are used, any 
      sensitivities or allergies will not be a problem.
  </p>

标签: javascripthtmlfunctionlocal-storage

解决方案


你可以尝试这样的事情:

function translate_fr() {
  document.getElementById(
    "intro"
  ).innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème`;
  localStorage.setItem("isFrench", "1");
}

function translate_eng() {
  document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only
  establishment that offers a full range of services 
  from complete grooming, bathing to boarding. You and 
  your pet will be thrilled to know that only professional, 
  natural and biodegradeable products are used, any 
  sensitivities or allergies will not be a problem.`;
  localStorage.setItem("isFrench", "0");
}

function check_translation() {
  const isFrench = localStorage.getItem("isFrench");
  return parseInt(isFrench);
}

function translate() {
  if (check_translation() === 1) {
    translate_fr();
    return;
  }

  translate_eng();
}

translate();

  • translate()在加载时触发函数。
  • 这可以检查本地存储值localStorage.getItem("isFrench");
  • 本地存储是字符串,因此转换为 int 但不是真正需要这样做。
  • 当用户执行您的 onClick 事件时将设置哪个(不在此示例中)
  • 如果为 1,则显示法语。
  • 如果为 0,则显示英文。

推荐阅读