JavaScript:访问外部 .js 文件中定义的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10864732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:18:23  来源:igfitidea点击:

JavaScript: Accessing Variables Defined in External .js Files

javascriptweb

提问by Bunkai.Satori

Possible Duplicate:
Dynamically Importing JavasScript

可能的重复:
动态导入 JavaScript

Is there a way to access variables which come from external imported JavaScript .js files?

有没有办法访问来自外部导入的 JavaScript .js 文件的变量?

In the external .js file I define a varialbe such as follows:

在外部 .js 文件中,我定义了一个变量,如下所示:

// JavaScript Document
var PETNAME = "Beauty";

After dynamically importing that code, I wish to access PETNAME variable, but I do not get the defined value:

动态导入该代码后,我希望访问 PETNAME 变量,但我没有得到定义的值:

alert("Pet Name: " + PETNAME);

What can be wrong, and is there a way to bring values from external .js code into the master JavaScript?

有什么问题,有没有办法将外部 .js 代码中的值带入主 JavaScript?

Thank you.

谢谢你。

回答by Sarfraz

To import JS dynamically, you need to consider onreadystatechangeand loadevents which are run when the script is parsed by the browser and available to you. You can use this function:

要动态导入 JS,您需要考虑浏览器解析脚本时运行的事件,onreadystatechange以及load哪些事件可供您使用。您可以使用此功能:

function getScript(url, callback) {
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   script.onreadystatechange = callback;
   script.onload = callback;

   document.getElementsByTagName('head')[0].appendChild(script);
}

And you can use it like this:

你可以像这样使用它:

getScript('path to your js file', function(){
  alert("Pet Name: " + PETNAME);
});

回答by Zefiryn

Make sure you are including external file before trying to access variable defined in it. Also make sure the variable in the external file is not defined inside function, in which case they range is limited to that function only. If this not helps try removing keyword varbefore variable, this will create global variable.

在尝试访问其中定义的变量之前,请确保包含外部文件。还要确保外部文件中的变量没有在函数内部定义,在这种情况下,它们的范围仅限于该函数。如果这没有帮助尝试var在变量之前删除关键字,这将创建全局变量。