简体   繁体   English

更改“ Window.location.href”时,将删除“窗口”对象上存储的属性

[英]Property stored on 'window' object is removed on changing the 'Window.location.href'

I'm defining a property ( say, myVar ) on window object (to use it as a global variable ), but the problem is when I take the user on some different page by making use of window.location.href that global variable is lost, and becomes undefined . 我在窗口对象上定义了一个属性(例如, myVar )(以将其用作全局变量),但是问题是当我通过使用window.location.href将用户带到某个不同的页面时,该全局变量是迷路,变得undefined

Why is this unexpected behaviour of window obj variable is showing up, is it related to scope, and how to correct it ? 为什么出现窗口obj变量的这种意外行为,它与作用域有关,以及如何纠正它?

The window object is built on page load. window对象建立在页面加载上。 After the page loads, you add the property and that stays with the object. 页面加载后,添加属性,该属性随对象一起保留。

When you redirect the user to another page, this is (obviously) interpreted as a new page, which means a new page load. 当您将用户重定向到另一个页面时,这(显然)被解释为一个新页面,这意味着要加载一个新页面。 By then, the window object is completely new. 届时, window对象将是全新的。

If you have to keep this variable between page refreshes, that a look at: 如果必须在刷新页面之间保留此变量,请查看:

sessionStorage sessionStorage

Syntax 句法

// 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 本地存储

Syntax 句法

// 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();

You could use the localStorage to store data that will persist between the pages of your website. 您可以使用localStorage来存储将保留在网站页面之间的数据。

localStorage.setItem('myVar', value);

localStorage.getItem('myVar'); // gives value

https://developer.mozilla.org/fr/docs/Web/API/Window/localStorage https://developer.mozilla.org/fr/docs/Web/API/Window/localStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM