Javascript 在函数外部初始化时变量不可访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2291252/
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
Variable not accessible when initialized outside function
提问by Nick Heiner
When I use code like this, it works fine:
当我使用这样的代码时,它工作正常:
function removeWarning() {
var systemStatus = document.getElementById("system-status");
systemStatus.innerHTML = "";
}
function indicateInvalidUsername() {
var systemStatus = document.getElementById("system-status");
systemStatus.innerHTML = "Invalid username";
}
However, when I then want to move the systemStatusto be a global variable, it doesn't work:
但是,当我想将 移动systemStatus为全局变量时,它不起作用:
var systemStatus = document.getElementById("system-status");
function removeWarning() {
systemStatus.innerHTML = "";
}
function indicateInvalidUsername() {
systemStatus.innerHTML = "Invalid username";
}
What am I supposed to be doing here?
我应该在这里做什么?
回答by MLefrancois
It really depends on where your JavaScript code is located.
这实际上取决于您的 JavaScript 代码所在的位置。
The problem is probably caused by the DOM not being loaded when the line
问题可能是由于在行时未加载 DOM 引起的
var systemStatus = document.getElementById("system-status");
is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.
被执行。您可以尝试在 onload 事件中调用它,或者最好使用 JavaScript 框架中的 DOM 就绪类型事件。
回答by Pekka
Make sure you declare the variable on "root" level, outside any code blocks.
确保在任何代码块之外的“根”级别声明变量。
You could also remove the varaltogether, although that is not recommendedand will throw a "strict" warning.
您也可以var完全删除,尽管不推荐这样做并且会发出“严格”警告。
According to the documentation at MDC, you can set global variables using window.variablename.
回答by lc.
My guess is that the system-statuselement is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?
我的猜测是在system-status运行变量声明之后声明元素。因此,在声明变量时,它实际上被设置为 null?
You should declare it only, then assign its value from an onLoadhandler instead, because then you will be sure that it has properly initialized (loaded) the element in question.
您应该只声明它,然后从onLoad处理程序分配它的值,因为这样您就可以确保它已正确初始化(加载)相关元素。
You could also try putting the script at the bottom of the page (or at least somewhere after the system-statuselement is declared) but it's not guaranteed to always work.
您还可以尝试将脚本放在页面底部(或至少在system-status声明元素之后的某个位置),但不能保证始终有效。
回答by NG.
Declare systemStatus in an outer scope and assign it in an onload handler.
在外部作用域中声明 systemStatus 并在加载处理程序中分配它。
systemStatus = null;
function onloadHandler(evt) {
systemStatus = document.getElementById("....");
}
Or if you don't want the onload handler, put your script tag at the bottom of your HTML.
或者,如果您不想要 onload 处理程序,请将您的脚本标记放在 HTML 的底部。
回答by Danny G
A global variable would be best expressed in an external JavaScript file:
全局变量最好用外部 JavaScript 文件表示:
var system_status;
Make sure that this has not been used anywhere else. Then to access the variable on your page, just reference it as such. Say, for example, you wanted to fill in the results on a textbox,
确保它没有在其他任何地方使用过。然后要访问页面上的变量,只需引用它即可。假设,例如,您想在文本框中填写结果,
document.getElementById("textbox1").value = system_status;
To ensure that the object exists, use the document ready feature of jQuery.
要确保对象存在,请使用 jQuery 的文档就绪功能。
Example:
例子:
$(function() {
$("#textbox1")[0].value = system_status;
});
回答by Travis J
To define a global variable which is based off a DOM element a few things must be checked. First, if the code is in the <head>section, then the DOM will not loaded on execution. In this case, an event handler must be placed in order to set the variable after the DOM has been loaded, like this:
要定义基于 DOM 元素的全局变量,必须检查一些事情。首先,如果代码在<head>节中,那么 DOM 将不会在执行时加载。在这种情况下,必须放置一个事件处理程序,以便在加载 DOM 后设置变量,如下所示:
var systemStatus;
window.onload = function(){ systemStatus = document.getElementById("system_status"); };
However, if this script is inline in the page as the DOM loads, then it can be done as long as the DOM element in question has loaded above where the script is located. This is because javascript executes synchronously. This would be valid:
但是,如果此脚本在 DOM 加载时内联在页面中,那么只要有问题的 DOM 元素已加载到脚本所在位置的上方,就可以执行此操作。这是因为 javascript 是同步执行的。这将是有效的:
<div id="system_status"></div>
<script type="text/javascript">
var systemStatus = document.getElementById("system_status");
</script>
As a result of the latter example, most pages which run scripts in the body save them until the very end of the document. This will allow the page to load, and then the javascript to execute which in most cases causes a visually faster rendering of the DOM.
作为后一个示例的结果,大多数在正文中运行脚本的页面都将它们保存到文档的最后。这将允许页面加载,然后执行 javascript,这在大多数情况下会导致 DOM 的视觉渲染速度更快。

