简体   繁体   中英

How do I access a variable in HTML document form external JavaScript file

If I have a variable in the <script> tags of an HTML document; lets call it example .

How can I access example in my JavaScript file?

 <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="css/example.css"> <link rel="icon" href="https://www.example.com/icon.png"> <title>Exsample</title> </head> <body> <script> var example = "example" </script> </body> 

Scripts loaded with <script> elements ( type=module aside) all share the same JS environment.

A variable created in the global scope by one will be available in all the others.

The only other proviso is that you can't access a variable before you create it.

 <script> var example = 1; </script> <script> console.log(example); </script> 

There is no difference between scripts where the script is loaded via src and those with the script provided inline.

You should be able to access it through window.example . If example is declared in a function, you won't be able to access it. Your external script must also appear after the variable declaration (or you can use the defer option on the script):

 console.log(window.example); 
 <script>var example = 'example';</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