如何在 html 和 javascript 中声明全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13352705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:31:53  来源:igfitidea点击:

How to declare global variable in html and javascript

javascriptpythonajaxdjango

提问by susanne

How can I declare a global variable in html and javascript for a django template page. I want to make display_language to be a global variables.

如何在 html 和 javascript 中为 django 模板页面声明全局变量。我想让 display_language 成为一个全局变量。

<script>
  function onChange(){
    if (xmlHttp.readyState==4 && xmlHttp.status==200) {
        //request is successful. So retrieve the values in the response
        display_language = xmlHttp.responseText.split(';');
        alert("response: " + display_language);
   }
}
 </script>


<html>
  <body>
     {% ifequal item.lang display_language %}
           {{item.text.strip}}
     {% endifequal %}
   </body>
</html>

回答by lostsource

Variables in JavaScript are implicitly global, so unless they are within a function and prefixed with the var keyword, they will be globally accessible

JavaScript 中的变量是隐式全局变量,因此除非它们在函数内并以 var 关键字为前缀,否则它们将是全局可访问的

This is global

这是全球的

<script type='text/javascript'>
    foobar = 'hello';
</script>

This is also global

这也是全球的

<script type='text/javascript'>
   function test() {
       foobar = 'hi';
   }
</script>

This is local

这是本地的

function test() {
    var foobar = 'world'; 
}