简体   繁体   English

从.js文件访问全局变量

[英]Access Global variable from a .js file

HTML file : HTML档案:

<HTML>

<HEAD>

  <Title>Testing</Title>
 </HEAD>
   <Body>
 <script src="Test.js" language="JavaScript" type="Text/JavaScript" >
      CreateVariables();
 document.write(glVarMsg3);

</script>

</Body>

</HTML>

.js file: .js文件:

function CreateVariables()
glVarMsg3="Global variable";

Friends please inform me what is the issue in this script? 朋友请告诉我此脚本有什么问题? why i can't be able to access variable from .js file? 为什么我无法从.js文件访问变量?

Firstly, that's invalid syntax for declaring a function. 首先,这是用于声明函数的无效语法。 You need braces: 您需要大括号:

function CreateVariables() {
    glVarMsg3="Global variable";
}

Secondly you can either set an src or script content, but not both. 其次,您可以设置src或脚本内容,但不能同时设置两者。 So you'd need: 因此,您需要:

<script src="Test.js"></script>
<script>
    CreateVariables();
    console.log(glVarMsg3);
</script>

A good place to start would be this MDN article on functions. 这篇关于功能的MDN文章是一个很好的起点。 Additionally, I hope this is just for learning/testing as the use of document.write and global variables in this way is discouraged. 另外,我希望这只是为了学习/测试,因为不鼓励以这种方式使用document.write和全局变量。

Just define your variables in global.js outside a function scope: 只需在函数范围之外的global.js中定义变量:

// global.js // global.js

var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file //其他js文件

function testGlobal () {
    alert(global1);
}

first just import 首先刚导入

<script src="Test.js">
</script>

after use 使用后

<script>
   CreateVariables();
   document.write(glVarMsg3);
</script>

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

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