我正在 window 对象上定义一个属性(例如,myVar)(将其用作全局变量),但问题是当我将用户在某些不同的页面上,通过使用 window.location.href
,全局变量会丢失,并变为 未定义
。
为什么窗口 obj 变量会出现这种意外行为,它与范围有关吗?如何纠正它?
最佳答案
window
对象是在页面加载时构建的。页面加载后,您添加属性并保留在对象中。
当您将用户重定向到另一个页面时,这(显然)被解释为新页面,这意味着新页面加载。届时,window
对象是全新的。
如果您必须在页面刷新之间保留此变量,请查看:
sessionStorage
语法
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
localStorage
语法
// The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().
localStorage.setItem('myCat', 'Tom');
// The syntax for reading the localStorage item is as follows:
var cat = localStorage.getItem('myCat');
// The syntax for removing the localStorage item is as follows:
localStorage.removeItem('myCat');
//The syntax for removing all the localStorage items is as follows:
// Clear all items
localStorage.clear();
关于javascript - 更改 'window' 时,存储在 'Window.location.href' 对象上的属性将被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57611423/