javascript - 返回页面时将重置脚本
问题描述
我在 Javascript 中构建了一个函数,它允许关注输入字段(类似于 Google 帐户登录)。该脚本的工作方式如下:
输入字段中有一个标题。一旦您单击对象并在其中写入内容,标题就会缩小并出现在字段上方。如果您完全删除文本并单击输入字段外,则焦点会消失。
在脚本中它看起来像这样:
const reg_inputs = document.querySelectorAll(".reg-input");
function addcl() {
const parent = this.parentNode.parentNode;
parent.classList.add("focus");
}
function remcl() {
const parent = this.parentNode.parentNode;
if (this.value == "") {
parent.classList.remove("focus");
return false;
}
}
reg_inputs.forEach((input) => {
input.addEventListener("focus", addcl);
input.addEventListener("blur", remcl);
return true;
});
问题是当他点击一个按钮时用户被带到另一个页面。如果用户现在返回到旧页面,则标题再次出现在输入字段中并覆盖了正常输入的文本。这看起来非常不友好,应该修复。我认为脚本将在返回时重置。有人能帮我吗?
解决方案
网页是无状态的。
这意味着如果您在网页上运行脚本,然后离开该页面并稍后返回该页面,则该页面将加载,就好像该脚本尚未运行(因为它尚未运行)。
然而,有一些方法可以向浏览器报告状态:
- 使用锚
#
(例如example.com/my-page.html#my-state
) - 使用查询字符串(例如
example.com/my-page.html?state=my-state
) - 饼干
- 使用
webStorage
(localStorage
或sessionStorage
)
更多关于webStorage
这webStorage API
创建了一个简单的键值存储,它在页面重新加载之间以及同一站点上的不同页面之间持续存在。
localStorage
和之间的区别在于sessionStorage
,当您离开网站时,任何sessionStorage
键和值都将被删除。
如果您愿意,webStorage API
可以将其视为(不完全是,但)有点像“客户端 cookie”。
使用起来相对无痛。
您需要记住的唯一一件事是每个webStorage
条目必须是 a string
(而不是 a number
、 anarray
或 an object
)。
即使这样也不是什么大问题,因为我们可以使用JSON
.
要将字符串值添加到localStorage
,请使用:
localStorage.setItem('myKey', 'myStringValue');
要从中检索该字符串值localStorage
,请使用:
let myValue = localStorage.getItem('myKey');
要检查密钥是否存在于 中localStorage
,请使用:
if (localStorage.getItem('myKey') !== null)
要从 中删除字符串值localStorage
,请使用:
localStorage.removeItem('myKey');
要从中删除所有字符串值localStorage
,请使用:
localStorage.clear();
推荐阅读
- sql - SSRS 报告垂直对齐更改为水平
- kubernetes - Kubernetes spec.ports required value 错误
- adonis.js - AdonisJs 找不到模块 'phc-bcrypt'
- python-3.x - 使用子进程立即退出 shell 脚本
- c++ - Can I use lambda as a hashing function in boost::multi_index hash-like interface?
- javascript - 如何使我的不和谐机器人具有自定义状态(discord.js)
- python - Python底图:将图例高度调整为地图区域
- java - 多级 @JsonTypeInfo 和 @JsonSubTypes
- angular - 行为主体的访问元素
- datetime - 在 MariaDB 中,如何选择每天最后一个事件并为其创建索引?