只是一个简单的问题。当您有一个包含普通函数、变量和其他内容的 js 文件时,该页面将被加载,然后在需要代码时使用。但我的问题是,例如,当您导航到另一个页面(例如使用 window.location.href)时,您创建的任何/所有变量会发生什么情况?它们还存在于记忆中吗?它们是否仍然可以访问?或者在您重新加载原始文件之前它们会永久消失吗?
1 回答
![?](http://img1.sycdn.imooc.com/5333a0350001692e02200220-100-100.jpg)
繁花如伊
TA贡献2012条经验 获得超12个赞
简短的回答:是的。
存储在 JS 文件中的每个变量都会丢失,或者说,每次重新加载页面或更改页面时都会创建一个新副本。 Window.location.href.
要在重新加载之间保留数据或使用变量的值,您应该使用客户端数据存储,例如sessionStorageorlocalStorage或cookies。
例如,让我们说使用可以使用的持久变量的值
let persist = "My data";
// Store it in localstorage
localStorage.set('persist', persist);
// Get the value of your saved variable to use it elsewhere
let persist = locastorage.get("persist");
//To delete the variable from storage
localStorage.removeItem('persist')
// To clear the entire storage
localStorage.clear()
语法与sessionStorage存储的值相同,但仅sessionStorage在页面会话期间可用。有关DOM 存储的更多信息,您可以在这里阅读。
添加回答
举报
0/150
提交
取消