初始化外部函数时变量不可访问 [英] Variable not accessible when initialized outside function

查看:102
本文介绍了初始化外部函数时变量不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数removeWarning(){
var systemStatus =的document.getElementById( 系统状态);
systemStatus.innerHTML =;


函数indicationInvalidUsername(){
var systemStatus = document.getElementById(system-status);
systemStatus.innerHTML =用户名无效;
}

然而,当我想要移动 systemStatus 是一个全局变量,它不起作用:

  var systemStatus = document.getElementById( 系统状况); 

函数removeWarning(){
systemStatus.innerHTML =;


函数indicationInvalidUsername(){
systemStatus.innerHTML =用户名无效;
}

我应该在这里做什么?

解决方案

这确实取决于您的JavaScript代码的位置。



当行不加载时,

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

被执行。你可以尝试在onload事件中调用它,或者理想地使用JavaScript框架中的DOM就绪类型事件。


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?

解决方案

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.

这篇关于初始化外部函数时变量不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆