猿问

加载新的 html 页面时,JS 变量是否会被破坏?

只是一个简单的问题。当您有一个包含普通函数、变量和其他内容的 js 文件时,该页面将被加载,然后在需要代码时使用。但我的问题是,例如,当您导航到另一个页面(例如使用 window.location.href)时,您创建的任何/所有变量会发生什么情况?它们还存在于记忆中吗?它们是否仍然可以访问?或者在您重新加载原始文件之前它们会永久消失吗?



烙印99
浏览 128回答 1
1回答

繁花如伊

简短的回答:是的。存储在 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 storagelocalStorage.clear()语法与sessionStorage存储的值相同,但仅sessionStorage在页面会话期间可用。有关DOM 存储的更多信息,您可以在这里阅读。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答