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

新手上路,请多包涵

我想将由另一个 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);
        });

原文由 Thabiso Prosper Ramokopu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 354
2 个回答

您甚至不需要在第一个文件中包含第二个文件即可使用该功能。如果第一个文件在您的代码中先于第二个文件被调用,您可以只引用该函数。

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

在 postInfoAndImages.js 中,只需调用有问题的函数:

 var imageList[];
imageList = myImageList();

原文由 elke_wtf 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 connexo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题