gpt4 book ai didi

JavaScript : Global variables become null after using location. 分配

转载 作者:行者123 更新时间:2023-11-28 19:48:45 24 4
gpt4 key购买 nike

我以这种方式有2个html和3个js文件

globals.js --> 
testIndex = 1;

login.html
//includes global.js and login.js. Fires event() function on a button click

login.js
function event()
{
window.testIndex = 2;
window.location.assign('index.html')
}

index.html
//includes globals.js and index.js
fires init() function onLoad

index.js
function init()
{
alert(window.testIndex);
}

分配工作正常,但 index.html 中的警报框始终显示 1。当我使用 window.location.assign 时,我的全局变量正在重新初始化。我需要传递一些变量(其中一些不是纯文本字符串,因此无法使用 url)。我该怎么办?

最佳答案

跨多个页面保存变量的最简单方法是使用 HTML5 sessionStorage。但是,此功能仅在现代浏览器(IE8+)中可用。请参阅here (html5polyfill.com)用于旧版浏览器的填充。

有关sessionStorage的更多信息可以找到here (MDN) .

session 存储示例:

globals.js --> 
sessionStorage['testIndex'] = 1;

login.html
//includes global.js and login.js. Fires event() function on a button click

login.js
function event()
{
sessionStorage['testIndex'] = 2;
window.location.assign('index.html')
}

index.html
//includes globals.js and index.js
fires init() function onLoad

index.js
function init()
{
alert(sessionStorage['testIndex']);
}

如果您需要存储非字符串对象,请首先使用JSON.stringify()将它们转换为字符串表示形式。 ,并使用 JSON.parse() 读回它们.

关于JavaScript : Global variables become null after using location. 分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23854983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com