导航到另一个页面(也使用相同的js文件)时,Javascript全局变量不会保留 [英] Javascript global variable does not persist when navigate to another page (which also uses same js file)

查看:101
本文介绍了导航到另一个页面(也使用相同的js文件)时,Javascript全局变量不会保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在angus.js中共享了这样的js代码

I have shared js code like this in angus.js

var g_colour;

function getcolour() {
  return g_colour;
}

function setcolour(colour) {
  g_colour = colour;
}

html第1页和第2页访问的内容如下:

Which is accessed by html pages 1 and 2 like this:

1.html:

<html>
<head>
<title>Global javascript example</title>
</head>
<body>
<a href="2.html">Page2</a>
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>

2.html:

<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
<a href="1.html">Page1</a>
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>

如果我在一个页面中设置颜色并导航到第2页,然后然后访问颜色,那么返回undefined。即我似乎在加载一个新的html页面时创建了一个新的g_colour实例。

If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.

我希望能够访问一种顶级变量可以在第1页中设置并在第2页中进行访问。如何在Javascript中执行此操作?

I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?

推荐答案

JS变量从不持久,但有两种解决方法:

JS variables never have been persistent, but there are two ways around this:


  1. Cookies

  2. 存储

除了最古老的浏览器之外,所有浏览器都支持Cookie,但它们可能非常难以使用且难以使用。最重要的是,您的浏览器会在每个页面加载时向服务器发送cookie,因此如果它仅由JavaScript使用,则效率非常低。

Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.

相反,您应该看一下存储选项。

Instead, you should probably look at the Storage option.

保存项目就像 localStorage.itemname = value; 读取一样简单 localStorage.itemname ,删除的字面值为 delete localStorage.itemname

Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname

这些值保存在页面加载中,但不会发送到服务器。

These values are saved across pageloads, but not sent to the server.

这篇关于导航到另一个页面(也使用相同的js文件)时,Javascript全局变量不会保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆