JavaScript:访问外部 .js 文件中定义的变量 [英] JavaScript: Accessing Variables Defined in External .js Files
问题描述
可能的重复:
动态导入 JavaScript
有没有办法访问来自外部导入的 JavaScript .js 文件的变量?
Is there a way to access variables which come from external imported JavaScript .js files?
在外部 .js 文件中,我定义了一个变量,如下所示:
In the external .js file I define a varialbe such as follows:
// JavaScript Document
var PETNAME = "Beauty";
在动态导入该代码后,我希望访问 PETNAME 变量,但我没有得到定义的值:
After dynamically importing that code, I wish to access PETNAME variable, but I do not get the defined value:
alert("Pet Name: " + PETNAME);
有什么问题,有没有办法将外部 .js 代码中的值带入主 JavaScript?
What can be wrong, and is there a way to bring values from external .js code into the master JavaScript?
谢谢.
推荐答案
动态导入 JS,需要考虑 onreadystatechange
和 load
事件由浏览器解析并可供您使用.您可以使用此功能:
To import JS dynamically, you need to consider onreadystatechange
and load
events which are run when the script is parsed by the browser and available to you. You can use this function:
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);
}
你可以这样使用它:
getScript('path to your js file', function(){
alert("Pet Name: " + PETNAME);
});
这篇关于JavaScript:访问外部 .js 文件中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!