如何使用另一个 JavaScript 文件中的变量?

How can I use a variable from another JavaScript file?

我有两个 html 页面,每个页面都有一个 js 文件。

当我点击 第 1 页 上的按钮时,它应该将变量 param 更改为 true 并将用户重定向到 第 2 页.

第 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 */

我尝试了 export/import 参数,但我得到了 Unexpected token 'export' error。我试过 type="module" 但它不起作用。我发现的示例是同一 html 页面中的两个 js 文件!

有人可以帮忙吗?

您可以从第一个文件导出变量

var first;

export { first }

并且在您的第二个文件中您可以导入该变量

import { first} from './first.js'

<script type="module" src='first.js'></script>

你不能那样共享变量状态。这两个页面是完全不同的实例,所以上下文也不一样。

选项 1. 当您从一个页面重定向到另一个页面时,您可以在第 2 页添加 URL 参数和 parse 它。

选项 2. 使用localStorage。我假设你们在讨论第 1 页和第 2 页时具有相同的来源,因此存储的数据将是可见的。

您不能从不同的页面访问变量,除非您使用 ajax 加载 page2.html。使用 cookie 或 localStorage

的替代方法

script1.js

var param = false;

edit.addEventListener("click", switchToOpenSession);
...
function switchToOpenSession() {
    param = true;
    localStorage.setItem('param', true)
    ...
}

然后在 script2.js

if (localStorage.getItem('param') == 'true') // note the quotes