Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - Variable not accessible when initialized outside function

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 systemStatus to be a global variable, it doesn't work:

var systemStatus = document.getElementById("system-status");

function removeWarning() {
    systemStatus.innerHTML = "";
}

function indicateInvalidUsername() {
    systemStatus.innerHTML = "Invalid username";
}

What am I supposed to be doing here?

question from:https://stackoverflow.com/questions/2291252/variable-not-accessible-when-initialized-outside-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...