簡體   English   中英

如何從另一個 JavaScript 文件導入變量?

[英]How can I import a variable from another JavaScript file?

我想將由另一個 JavaScript 文件 ( imageUploadDisplay.js ) 填充的數組 ( imageArray[] ) 導入另一個 JavaScript 文件函數 ( postInfoAndImages.js )。 下面是我嘗試使用的imageUploadDisplay.js函數。

// In my imageUploadDisplay.js

var imageList = [];

function myImageList() {

    return imageList;
}

正如其他人所解釋的,我使用以下 jQuery 將imageUploadDisplay.js導入 JavaScript postInfoAndImages.js

// In my postInfoAndImages.js
var imageList = [];

$.getScript('imageUploadDisplay.js', function () {
            // Script is now loaded and executed.
            alert("Script loaded, but not necessarily executed.");
            imageList = myImageList(); // Picture array
            console(imageList);
        });

對於 Firefox、Chrome、Safari 和 Opera 等現代瀏覽器,只需使用 ES6 模塊。

在你的imageUploadDisplay.js創建一個命名的export

// imageUploadDisplay.js
var imageList = [];

export function myImageList() {
  return imageList;
}

然后只需導入函數:

// then in postInfoAndImages.js
import { myImageList } from './path/to/imageList.js';

var imageList = myImageList();

在您的 HTML 中,您不再需要包含imageUploadDisplay.js (這是通過在運行時導入完成的)。

相反,包含type="module"的導入腳本:

<script type="module" src="./path/to/postInfoAndImages.js"></script>

您需要處理導出和導入

// File imageUploadDisplay.js

let myImageList = () => {
    return imageList;
}

export default imageList

然后將其導入到另一個文件中

// postInfoAndImages.js

import imageList from "./imageUploadDisplay"

// -> Do something with imageList

您甚至不需要在第一個文件中包含第二個文件即可使用該函數。 如果第一個文件在第二個之前在您的代碼中被調用,您可以只引用該函數。

<script type="text/javascript" src="imageUploadDisplay.js"/>
<script type="text/javascript" src="postInfoAndImages.js"/>

在 postInfoAndImages.js 中,只需調用有問題的函數:

var imageList[];
imageList = myImageList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM