[英]Access variables from another JavaScript file
我需要从renderermain.js
获取变量currentID
并在renderermem.js
中使用它。
但是,我需要这样做而不必将其添加到mem.html
:
<script src="renderermain.js"></script>
<script src="renderermem.js"></script>
因为我不能把这两者混在一起。
我试过了:
渲染器main.js
globalVariable={currentID:activeID};
渲染内存.js
var currentID = globalVariable.currentID;
但这不起作用。
注意:此时我将 html 个文件从main.html
(使用renderermain.js
)切换到mem.html
(使用renderermem.js
)。
有人有什么想法吗?
谢谢。
web页之间传递变量基本上有两种方式。 第一种方法是使用 sessionStorage 或 localStorage。 第二种方法是使用带有 URL 的查询字符串。
要使用 sessionStorage 或 localStorage:这位于第一个 web 页面中:
// "myVariable" is the sessionStorage variable name
// "variable_one" is the variable string value
sessionStorage.setItem("myVariable", "variable_one);
// This goes in the second web page:
// Retrieve the sessionStorage variable
var myVariable = sessionStorage.getItem('myVariable');
Query String with URL:传递一个字符串作为参数。
例子:
<a href="filename.html?data1|data2|data3">Go to filename</a>
单击文件名的 Go 时,文件名.html 将加载查询字符串
"?data1|data2|data3"
附加到地址栏中的文件名。 要将查询字符串放入变量中,请使用:
var queryString = location.search.substring(1);
变量 queryString 现在具有值
"data1|data2|data3"
要将这些分解成单独的变量,请使用 split:
var a = queryString.split("|");
// which creates an array
然后从数组中取出值并将它们放入变量中:
var value1 = a[0];
var value2 = a[1];
var value3 = a[2];
现在:
value1 == "data1", value2 == "data2", value3 == "data3"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.