如何在 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
How to declare global variable in html and javascript
提问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';
}