[英]Access variables from another JavaScript file
I need to get a variable currentID
from renderermain.js
and use it in renderermem.js
.我需要从
renderermain.js
获取变量currentID
并在renderermem.js
中使用它。
However, I need to do this without having to add this to mem.html
:但是,我需要这样做而不必将其添加到
mem.html
:
<script src="renderermain.js"></script>
<script src="renderermem.js"></script>
Because I cannot mix these two.因为我不能把这两者混在一起。
I have tried:我试过了:
renderermain.js渲染器main.js
globalVariable={currentID:activeID};
renderermem.js渲染内存.js
var currentID = globalVariable.currentID;
But this doesn't work.但这不起作用。
Note: I am switching html files at this point from main.html
(using renderermain.js
) to mem.html
(using renderermem.js
).注意:此时我将 html 个文件从
main.html
(使用renderermain.js
)切换到mem.html
(使用renderermem.js
)。
Does anyone have any ideas?有人有什么想法吗?
Thanks.谢谢。
Basically there are two ways to pass variables between web pages. web页之间传递变量基本上有两种方式。 The first method is to use sessionStorage, or localStorage.
第一种方法是使用 sessionStorage 或 localStorage。 The second method is to use a query string with the URL.
第二种方法是使用带有 URL 的查询字符串。
To use sessionStorage or localStorage: This goes in the first web page:要使用 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: Pass a string as a parameter. Query String with URL:传递一个字符串作为参数。
Example:例子:
<a href="filename.html?data1|data2|data3">Go to filename</a>
When Go to filename is clicked, filename.html is loaded with the query string单击文件名的 Go 时,文件名.html 将加载查询字符串
"?data1|data2|data3"
appended to the filename in the address bar.附加到地址栏中的文件名。 To get the query string into variables, use:
要将查询字符串放入变量中,请使用:
var queryString = location.search.substring(1);
The variable queryString now has the value变量 queryString 现在具有值
"data1|data2|data3"
To break these out into individual variables use split:要将这些分解成单独的变量,请使用 split:
var a = queryString.split("|");
// which creates an array
Then get the values out of the array and put them into variables:然后从数组中取出值并将它们放入变量中:
var value1 = a[0];
var value2 = a[1];
var value3 = a[2];
Now:现在:
value1 == "data1", value2 == "data2", value3 == "data3"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.