jquery 如何从另一个JavaScript文件导入变量?

dtcbnfnu  于 2023-02-03  发布在  jQuery
关注(0)|答案(3)|浏览(213)

我想导入一个数组(imageArray[]),这个数组由另一个JavaScript文件(imageUploadDisplay.js)填充到另一个JavaScript文件函数(postInfoAndImages.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);
        });
zdwk9cvp

zdwk9cvp1#

对于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>
vlf7wbxs

vlf7wbxs2#

您需要使用exports and imports

// File imageUploadDisplay.js

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

export default imageList

然后将其导入到其他文件中

// postInfoAndImages.js

import imageList from "./imageUploadDisplay"

// -> Do something with imageList
4nkexdtk

4nkexdtk3#

你甚至不需要在第一个文件中包含第二个文件来使用这个函数,如果第一个文件在第二个文件之前被调用,你可以直接引用这个函数。

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

在postInfoAndImages.js中,只需调用相关函数:

var imageList[];
imageList = myImageList();

相关问题