简体   繁体   English

如何在HTML文档形式的外部JavaScript文件中访问变量

[英]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; 如果我在HTML文档的<script>标记中有一个变量; lets call it example . 让我们称之为example

How can I access example in my JavaScript file? 如何访问JavaScript文件中的example

 <!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. 加载了<script>元素(不包括type=module )的<script>都共享相同的JS环境。

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. 通过src加载脚本的脚本与内联提供脚本的脚本之间没有区别。

You should be able to access it through window.example . 您应该能够通过window.example访问它。 If example is declared in a function, you won't be able to access it. 如果在函数中声明了example ,则将无法访问它。 Your external script must also appear after the variable declaration (or you can use the defer option on the script): 您的外部脚本也必须出现在变量声明之后(或者您可以在脚本上使用defer选项):

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

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

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