简体   繁体   English

我可以从外部文件加载JavaScript数组吗?

[英]Can I load a javascript array from an external file?

My app uses a lookup table that is embedded in the script. 我的应用程序使用嵌入在脚本中的查找表。 For ease of maintenance I would like to load this table from an external file. 为了便于维护,我想从外部文件加载该表。 What is the best way to accomplish this? 做到这一点的最佳方法是什么? I am using the table to specify an image to be loaded on a click event. 我正在使用表格指定要在click事件上加载的图像。

var categoryTable = {
    "volunteer": "d3_files/images/thunderx64.png",
    "organization": "d3_files/images/cloudyDayx64.png",
    "air":"nothing"
};

you can make a function in other js file that return this array. 您可以在其他js文件中创建一个返回此数组的函数。 load that file and call function to get this array. 加载该文件并调用函数以获取此数组。

An external .js file can contain any valid Javascript. 外部.js文件可以包含任何有效的Javascript。 Putting a variable assignment in it is just fine. 将变量赋值放入其中就可以了。

It will have to be a global variable for it to be visible to code in other files. 它必须是全局变量,才能在其他文件中的代码中可见。

Take a look at jQuery getScript() Method: 看一下jQuery getScript()方法:

Quoting from Jquery site: 从Jquery网站报价:

Description: Load a JavaScript file from the server using a GET HTTP request, then execute it. 说明:使用GET HTTP请求从服务器加载JavaScript文件,然后执行它。

If your table is JS, then this should help you. 如果您的表是JS,那么这将为您提供帮助。 However, I think that a better approach would be to rewrite the table code and give it a JSON or XML form. 但是,我认为更好的方法是重写表代码并为其提供JSON或XML形式。 It is is table, then it should be adaptable to some standard form of data representation rather than some custom JS code. 它是表,因此它应该适用于某种标准形式的数据表示形式,而不是某些定制的JS代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM