[英]How can I use a variable from another JavaScript file?
我有兩個 html 頁面,每個頁面都有一個 js 文件。
當我單擊第 1 頁上的按鈕時,它應該將變量參數更改為 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 */
我嘗試導出/導入參數,但出現Unexpected token 'export' error
。 我試過type="module"
但它不起作用。 我發現的樣本是同一個 html 頁面中的兩個 js 文件!
有人可以幫忙嗎?
您不能從不同的頁面訪問變量,除非您使用 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
您可以從第一個文件導出變量
var first;
export { first }
在您的第二個文件中,您可以導入該變量
import { first} from './first.js'
或者
<script type="module" src='first.js'></script>
你不能像那樣共享可變狀態。 這兩個頁面是完全不同的實例,所以上下文是不一樣的。
選項1。當您從一個頁面重定向到另一個頁面時,您可以添加 URL 參數並在第 2 頁上解析它。
選項2. 使用localStorage 。 我假設您在第 1 頁和第 2 頁上交談時具有相同的來源,因此存儲的數據將是可見的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.