[英]How can I use a variable from another JavaScript file?
I have two html pages, each with a js file.我有两个 html 页面,每个页面都有一个 js 文件。
When I click on a button on page 1 , it should change a variable param to true and redirect the user to page 2 .当我单击第 1 页上的按钮时,它应该将变量参数更改为 true 并将用户重定向到第 2 页。
In page 2 I have to check if param = true and then continue my script.在第 2 页,我必须检查param = true ,然后继续我的脚本。
<div class="container-fluid" id="about">
<div class="row">
<div id="mainsubtitle">Page 1</div>
<button id="edit" type="button">Go to page 2</button>
</div>
</div>
var param = false;
edit.addEventListener("click", switchToOpenSession);
...
function switchToOpenSession() {
param = true;
...
}
<div class="container-fluid">
<div class="row">
<div>Page 2</div>
<button id="create" type="button">Create account</button>
</div>
</div>
if (param)
/* do this */
I tried export/import param but I got Unexpected token 'export' error
.我尝试导出/导入参数,但出现
Unexpected token 'export' error
。 I tried type="module"
but it doesn't work.我试过
type="module"
但它不起作用。 The samples that I found was two js files in the same html page!我发现的样本是同一个 html 页面中的两个 js 文件!
Can someone help please?有人可以帮忙吗?
you cannot access variable from different page, except you load page2.html
using ajax. Alternative way using cookie or localStorage
您不能从不同的页面访问变量,除非您使用 ajax 加载
page2.html
。使用 cookie 或localStorage
的替代方法
script1.js
var param = false;
edit.addEventListener("click", switchToOpenSession);
...
function switchToOpenSession() {
param = true;
localStorage.setItem('param', true)
...
}
then in script2.js
然后在
script2.js
if (localStorage.getItem('param') == 'true') // note the quotes
you can export the variable from first file您可以从第一个文件导出变量
var first;
export { first }
and in your second file you can import that variable在您的第二个文件中,您可以导入该变量
import { first} from './first.js'
OR或者
<script type="module" src='first.js'></script>
You can't share variable states like that.你不能像那样共享可变状态。 These two pages are totally different instances, so the context is not the same.
这两个页面是完全不同的实例,所以上下文是不一样的。
Option 1. When you redirect from one page to another you can add URL param and parse it on page 2.选项1。当您从一个页面重定向到另一个页面时,您可以添加 URL 参数并在第 2 页上解析它。
Option 2. Use localStorage .选项2. 使用localStorage 。 I assume you have the same origin while talking on page 1 and page 2 so the stored data will be visible.
我假设您在第 1 页和第 2 页上交谈时具有相同的来源,因此存储的数据将是可见的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.