简体   繁体   中英

Access Global variable from a .js file

HTML file :

<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:

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?

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. 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. Additionally, I hope this is just for learning/testing as the use of document.write and global variables in this way is discouraged.

Just define your variables in global.js outside a function scope:

// global.js

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

// other js-file

function testGlobal () {
    alert(global1);
}

first just import

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

after use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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