javascript - 带有功能的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>
解决方案
你可以尝试这样的事情:
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,则显示英文。
推荐阅读
- javascript - 如何摆脱 D3JS 中的嵌套 selectAll?
- elixir - ecto 变更集为现有添加关联
- python - dask 数组分块如何用于三个或更多维度?
- python - 如何在 python pandas 中找到两组之间的差异?
- java - 具有本地文件依赖项的 Maven 项目构建错误 501
- r - 编码这个适应度函数的最快方法是什么?
- ios - 有没有办法检查 NSPhotoLibraryAddUsageDescription 权限是被授予还是被拒绝?
- android - 如何使用 Boost Asio 在 Android 上获取我的本地 udp ip 地址?
- javascript - 输入后如何过滤json?
- r - R中的列选择错误与应用循环